#web-development
2 messages · Page 233 of 1
----- flask code -------
@app.route("/start")
this executes func1()
def start():
func1(param1, param2)
return render_template("index.html")
@app.route("/download")
this is for downloading a file when the button is clicked
def download():
file = func2()
return send_file(file)
-------python code (backend) -----
global_var = ""
def func1(k8s, name):
global global_var
global_var = f'{name}{date.now()}.pcap'
def func2():
global global_var
file = global_var
return file
Yes ... if i call func2() in the /start route it works fine but this doesnt work in separate routes
Yes # global_var = ""
indeed, func2() returns a blank global_var
is there a way to store the value returned by func1() for later use when i call func2()?
yes it is
though i think you need to use sql
for string the val of func2() you might require sql
if you cannot manage with the global var
sqlite3 comes preinstalled with python so yes you can
i'll try it if it doesnt complicate things 😅
yes i will just give you the formatted code
Hello
guys
I need help with something
I'm using selenium and python and i want to submit a captcha token
but I can do so because there is no submit button
I tried making a button
but it didn't really do anythig
hey i figured out another way
this will only use 2 lines
Without sql ?
@app.route("/start")
func_1_val = str()
# this executes func1()
def start():
global func_1_val
func_1_val = func1(param1, param2)
return render_template("index.html")
@app.route("/download")
# this is for downloading a file when the button is clicked
def download():
file = func2()
return send_file(file)
-------python code (backend) -----
global_var = ""
def func1(k8s, name):
global global_var
global_var = f'{name}{date.now()}.pcap'
return global_var
def func2():
global global_var
file = global_var
return file```
yes that is done
@bleak adder
@bleak adder
Thank you @orchid hamlet i will try it
I just stored the value by returning func1 to func_1_val
i hope it will work when i call func2() 🤞
oh yes the value is stored in func_1_val, so edit your code accordingly
Alright ... thank you 😋
I'm building a form in Flask using Flask-WTF and wtforms. Everything works except for my BooleanFields, which always return false -even when checked on the front end.
In my form class, I just have them listed as:
field_name = BooleanField('field_label')
Am I missing something?
why the extra ' in field label for?
Typo
can you send the code?
Standby
Sorry, its too long - one sec.
Ugh lol, nevermind. I figured it out. Copying the relevant jinja code made me spot the issue.
no problem.
Thats the problem with coding at 2 in the morning.
I had value = "" as an attribute of each boolean field in my jinja template.
So I guess it was forcing them all to be false.
removed that, and now it works as expected.
Not sure why I put that in there to begin with.
oh so the value kind of reseted
¯_(ツ)_/¯
It's Impossible in the model bcz you have to migrate everytime anyone logged in or logout, then the solution should be in the view, your author field should be updated everytime you go to this form page by enter the logged in user
{% extends "layout.html" %}
{% block title %}About{% endblock %}
{% block body %}
<img src="about.jpg" alt="About" width="500" height="600">
{% endblock %}
This is my HTML code to display an image. However, the image does not show, and instead the alt text does.
the image src is incorrect then
Hi, I am integrating mysql and flask and I'm trying to search for a matching substring in a mysql row in my flask web api.
I got this code in another file listing.py
def getTravelPackageBySubstring(cls,substring):
try:
dbConn = DatabasePool.getConnection()
db_Info = dbConn.connection_id
print(f"Connected to {db_Info}");
cursor = dbConn.cursor(dictionary=True)
sql = "SELECT * from `travel listing` where description or country LIKE '%",(substring),'%"'
substring=cursor.execute(sql,(substring,))
substring = cursor.fetchall()
return substring
finally:
dbConn.close()
print ("release connection")
How can I get it to run in app.py?
I tried
@app.route('/listing/<string:substring>')
def getTravelPackageBySubstring(substring):
try:
jsonListing=TravelPackage.getTravelPackageBySubstring(substring)
jsonListing={"Travel Listing":jsonListing}
return jsonify(jsonListing)
except Exception as err:
print (err)
return {},500
and it gives an error ''tuple' object has no attribute 'encode'
have u figured this out?
i was doing the same thing rn
Could be what you're passing to cursor.execute - Is the first argument (the variable sql) the type string or tuple?
@tribal onyx
Looks like the variable sql is of type tuple - I don't know if it should be.
>>> substring='foobar'
>>> sql = "SELECT * from `travel listing` where description or country LIKE '%",(substring),'%"'
>>> print(sql)
("SELECT * from `travel listing` where description or country LIKE '%", 'foobar', '%"')
The reason it probably errors with the message tuple object has no attribute 'encode' is the method cursor.execute calls encode(...) on the first argument you pass it, which is of type tuple and not type string
That line should use the + operator to concatenate those strings (Actually this is vulnerable to SQL Injection, so...you may want to use prepared statements) instead of using , to make sure the type is string and not tuple
How much OOP should I know? I've been doing only leetcode lately but was wondering about OOP
I am trying to make a chat room, but for some reason the box that loads in messages (the div) extends the whole web page when it is filled with messages, but I want the box (it's the div) to scroll when it runs out of space, so it can fit more messages. But, I don't know how to do that. ```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Chat App</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.1/socket.io.js"></script>
<style>
#sendBtn {
display: inline-block;
vertical-align: middle;
transform: translateZ(0);
box-shadow: 0 0 1px rgba(0, 0, 0, 0);
backface-visibility: hidden;
-moz-osx-font-smoothing: grayscale;
transition-duration: 0.3s;
transition-property: transform;
}
#sendBtn:hover,
#sendBtn:focus,
#sendBtn:active {
transform: scale(1.1);
}
</style>
<h1 style="text-align:center; font-family: Monospace, Arial">Chat App</h1>
</head>
<body style="text-align:center; font-family: Monospace, Arial; font-size: 14pt">
<script type="text/javascript">
$(document).ready(function() {
var socket = io.connect("server")
socket.on('connect', function() {
socket.send("User Connected!");
});
socket.on('message', function(data) {
$('#messages').append($('<p>').text(data));
});
$('#sendBtn').on('click', function () {
socket.send($('#username').val() + ': ' + $('#message').val());
$('#message').val('');
});
})
</script>
<div id="messages" style="margin: 0 auto; width: 60%; text-align: left; min-height: 300px; border: 1px solid black;">
</div>
<input type="text" id="username" placeholder="Username">
<input type="text" id="message" placeholder="Message">
<button id="sendBtn">Send</button>
</body>
</html>```
is here someone that could help me with making a cta that redirects to another html within a flask app
!d flask.redirect
flask.redirect(location, code=302, Response=None)```
Create a redirect response object.
If [`current_app`](https://flask.palletsprojects.com/en/latest/api/#flask.current_app "flask.current_app") is available, it will use its [`redirect()`](https://flask.palletsprojects.com/en/latest/api/#flask.Flask.redirect "flask.Flask.redirect") method, otherwise it will use [`werkzeug.utils.redirect()`](https://werkzeug.palletsprojects.com/en/2.1.x/utils/#werkzeug.utils.redirect "(in Werkzeug v2.1.x)").
I see
Hi, I am currently trying to set up a login system for my website and I was wondering if anyone could verify if would this would work: https://paste.pythondiscord.com/ubebanupel
Then I am referencing
@login_manager.user_loader
def load_user(user_id):
return User.get(user_id)
@home_bp.before_request
def before_request():
if login_manager.is_authenticated and request.endpoint != 'login':
return redirect(url_for('login'))``` in a routes file that gets imported into the create_app function
I've set up a self signed localhost cert for my staging server. It works, but I'm getting this error from this nginx config
upstream django_app {
server web:8081;
}
server {
listen 80;
server_name localhost;
rewrite ^(.*) https://localhost$1 permanent;
location / {
proxy_pass http://django_app;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}
location /.well-known/acme-challenge/ {
allow all;
root /var/www/certbot;
}
}
server {
listen 443 ssl;
ssl_certificate /etc/ssl/certs/localhost.crt;
ssl_certificate_key /etc/ssl/certs/localhost.key;
ssl_ciphers HIGH:!aNULL:!MD5;
server_name localhost;
location / {
proxy_pass http://django_app;
}
location /static/ {
alias /home/app/web/staticfiles/;
}
location /media/ {
alias /home/app/web/mediafiles/;
}
}
DisallowedHost at /
Invalid HTTP_HOST header: 'django_app'. The domain name provided is not valid according to RFC 1034/1035.
Request Method: GET
Request URL: http://django_app/
Django Version: 4.0.4
Exception Type: DisallowedHost
Exception Value:
Invalid HTTP_HOST header: 'django_app'. The domain name provided is not valid according to RFC 1034/1035.
Exception Location: /usr/local/lib/python3.9/site-packages/django/http/request.py, line 149, in get_host
Python Executable: /usr/local/bin/python
Python Version: 3.9.6
What can I change to make this work for https://127.0.0.1/ on a safe stage server?
is this as simple as adding django_app to ALLOWED_HOSTS lol
that did not seem to work
https://stackoverflow.com/questions/33097700/django-error-external-ip-invalid-http-host-header-domain-com this might help
nah, not really i already had all that stuff set
the nginx config is working, it django that seems to not like this.
I wish that django had built in configs to understand, "This is a staging server. Just go with it."
hey, could someone please explain unit testing mocking to me?
im learning nestjs rn, and one thing i noted is that most tests in the most popular test repo (https://github.com/jmcdo29/testing-nestjs) use mock functions for testing
isn't that approach objectively wrong? since we always know what mock function returns, the test is always gonna pass, while the actual controller logic is not tested at all
let's say we have mock func of findall returning array 1, 2, 3
then we test this function for element at index 2 being 3, and ofc, test passes
but actual logic used in controller is not tested at all this way
what's the point of mocking then?
the solution to my problem if anyone cares? remove underscores in nginx.conf... django_app becomes djangoapp; then it has to be added to ALLOWED_HOSTS
i created a news model that admin can create news and show it on pages now each user can comment on posts so i created comment form inherited the modelForm
now if i display my form it shows the user_id and news_id which is supposedly filled up automatically depending on the post selected and currently logged in user
or should i use forms.Form?
@stable bear
The kms_driven key does not exist.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Use the .get(key, default) method instead to provide a default value when the key is not found. And if you're sure the key must exist, then it's probably missing. Debug the part where you're adding parameters to your GET request
Filling form fields automatically should be handled by the views. You can access the current user using request.user and you should get the news instance using
news_obj = News.objects.get(id=id)
If you pass the id as a path parameter
Hello, i need to use js in my project but i'm not really good at it so i need to complete this task:
i have an html table with buttons on each row some i'd like to have the row data whenever i click the button present in that row
How can i do that with js??
Any code examples ?
My scrollbar is moving but the page itself doesnt move, any ideas?
maybe you have position: fixed on fullscreen element (blocking main page)
ah i see
thansk ill check now
ok yes you are right, sorry that was a very dumb issue. i am still quite new to this
Hi, I built my project using Angular, Django and PostgreSQL
I have never deployed my projects before
I want to deploy on Heroku or AWS
Any tutorials or documentations please?
something like this?
and in my template i just remove the 2 fields as it will be filled on the views.py ?
or should i just not use modelForms for this? its just the comment model
Maybe you should use the initial argument when creating the form instance, and the pass the like thisuser and news
user_id = request.user
news_id = id # or maybe you need the object, not the id
form = CommentForm(initial={"user_id": user_id, "news_id": news_id})
It's fine to use ModelForm
Hello
I am using an html form in Flask.
And i have an input box. Someone managed to send an URL through that text input box. 🙂
How can i transform this into a harmless string? ```html
<a onmouseover="alert('reason')" href="https://www.google.com">google</a>
how do i add the comment to the form?
i have made a webpage which shows the youtube videos based on the query result using the youtube data api
i want to call the YouTube API continuously in background (async) with some interval (say 1 min) for fetching the latest videos for the search query and it updates the webpage every 1 min automatically
how can i implement that in django?
Dumb way: Client side javascript REST API calls in a loop to your Django Rest Framework endpoint
Smart way: Web sockets (Feel free to check Django Channels in addition for Django with web sockets flavour)
I'm adopting lodash into my project. Would this be the correct way to convert this function? ```ts
const rows = {} as Record<string, string[]>;
for (const item of selectedItems) {
const [name, rack] = splitLabRow(item);
if (!(name in rows)) {
rows[name] = [];
}
rows[name].push(rack);
}
return Object.entries(rows);
to
```ts
return _.chain(selectedItems)
.map(splitLabRow)
.groupBy(0)
.mapValues((v) => _.map(v, 1))
.toPairs()
.value();
which one is the easy way cause i m on a deadline here
also pls share any yt video or resource if any..
dumb way is easiest
though it will require from you some level of Javascript understanding how to do it 🤔
Hey I’m on windows 10. And vscode isn’t recognizing pipenv
Working on a project using Django and I can’t get venv setup
Yup did that and went in manually and into environment variables and set it up
Still not working
Possibly, how can I switch?
set your path and restarted your shell?
Yup did that too
just log off and back in
Did that too 😂
are you using cmd bash or powershell?
Power shell
run get-command pipenv
if it can't find it, double check the path via $Env:Path
If all else fails, use pipx. https://pypa.github.io/pipx/
execute binaries from Python packages in isolated environments
It installs your applications to ~/.local/bin
Then source /bin/local/activate to set venv right?
no, that's handled by pipenv
Oh
It's been a while since I used pipenv (I use poetry now), but I think it's just pipenv install <package> then pipenv run yourcommand
there may also be a pipenv shell command.
Okay bet I’ll try that
do u have a example code?
@frank shoal hey got pipenv to work, do you have the documentation site for it>
its normal for me...
This isn't cursive for you?
I wonder why it's different in firefox
btw, this is the actual docs page.
https://pipenv.pypa.io/en/latest/
The old one was from when it wasn't part of pypa
Let's supposed I'm making a Django user model that should have a dozen attributes I've assigned, with many of them belonging to other models. Should I explicitly state every single one of those attributes on the user model or would just stating them on the attribute models be enough?
firefox?
Yep
it's actually cursive for some reason
Chrome is completely broken for me, so I cant test it on there
Any ideas why the "User" is repeated twice in my django admin interface? I want to use a custom User field, but not if I won't be able to use the built-in authentication.
https://prnt.sc/8C4e0Zx89e5n
flask is pretty useful
You created two different views for users
Check your views.py
Sorry for the late reply
I think I had two models instead
Question: let's say I have 3 models: user, country, and region.
Each user has a region and a country, and each region has a country.
How can I make it so that when either I'm in my admin panel and adding new users, or users are registering on the website, I/they only get to see the regions depending on the country they've selected(Since I wouldn't want to show them regions belong to other countries)?
Exactly when does heroku delete user uploaded files from its ephemeral storage? I'm new to webdev,
making a django webapp that takes user uploaded files(text files; pdf,docx,epub etc) and does some processing on it and shows an output in the form of a plotly graph. I am fine with heroku deleting the file after I'm done displaying the graph to the end user. Will heroku fit these specifications?
href="{{ url_for('static', path='styles/index.css') }}"
File "Z:\Code\Friends Computer\lib\site-packages\starlette\templating.py", line 72, in url_for
request = context["request"]
File "Z:\Code\Friends Computer\lib\site-packages\jinja2\runtime.py", line 331, in __getitem__
raise KeyError(key)
KeyError: 'request'```
jinja2 giving this err
fastapi
i think Heroku doesn't deal with user uploaded files
for that u need to integrate AWS
Oh? I was under the impression that it does
https://stackoverflow.com/questions/15637018/uploading-files-on-heroku
I think this is for people who want to store the files long term
I don't care if it gets deleted in 5mins or whenever the dyno restarts
https://devcenter.heroku.com/articles/dynos#isolation-and-security according to this the dyno restarts when we push new changes or in a fixed time every day whichever is earlier
can someone help with this error please => from rest_framework_simplejwt.tokens import RefreshToken ModuleNotFoundError: No module named 'rest_framework_simplejwt' my settings.py file => 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', # <-- And here ], im confused because i have the module installed
So I'm creating one django model for versioning.. so what is the correct django model naming convention? Should I name the django model as Versioning or just Version?
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Website</title>
</head>
<body bgcolor="black">
<h1>heading</h1>
</body>
</html>
h1{
color: white;
font-family: 'Courier New', Courier, monospace;
}
Anyone know why this does not display anything?
pls ping on response
are you asking why you css isnt displaying? @main sorrel
You havent linked your stylesheet
nah it happens haha
Does anyone here use FastAPI and the companion SQLModel? I've done an app with them and it's all fine and great until I need to delete lots of rows. I can't figure out how to do a "delete from x where something something".
I can select all the objects that should be deleted and could probably do a session.delete(obj) in a loop, but that sounds beyond daft.
how do I change the format of 2022-06-28T05:44:45Z in the django template?
google how the process of deleting in bulks is availbale
i am not sure about the details too
but it should be possible to request deleting all necessary objects in one sent bulk request to db
hey
i was wondering if there were any quick web libraries to display some statistics?
i have a project which tracks individual stocks and being able to show their current prices, charts, etc on a simple list web UI would be helpful
I asked here because my searches turned up nothing. The session object doesn’t work like the one in SQLAlchemy.
But did you installed it in your virtualenv?
I think this is what you need: https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#date
well I did a quick search here and found this that might help you https://stackoverflow.com/a/53501451/3716354
im not using virtualenv
It sounds like regular used Data Science tools
panda is used together with plot something libs
They will draw result in picture format, which you can show in web
You could check advices from people in #data-science-and-ml , or just checking stuff used by people in tutorials at https://kaggle.com
Or actually it can be googled as panda plot, https://pandas.pydata.org/docs/user_guide/visualization.html, there are libs for 2D and for 3D visualizations
Docker then?
no just normal terminal
well I would strongly advise you to use a virtualenv then. Create one with python -m venv .venv it will create a directory called .venv where you can activate by source .venv/bin/activate then inside that env you can install all your packages. The problem your facing is really common when you're installing packages globally
hmmm ill try thanks
But that’s raw SQLAlchemy. I have an SQLModel session.
i got this error => ```Error: Command '['/Users//Desktop/occupy/backend/.venv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1.````
i tried installing venv with sudo and got this => sudo: apt-get: command not found
Because it seems that you're already inside a .venv
oh really
If you have python3 you don't need to install venv, it already comes with Python
oh wondeful
run the following: which python
/usr/bin/python
im using python3 because for every command i have to run python3 like python3 manage.py runserver
That's weird. What is your python version? and which OS you're using (windows I suppose)
You might also have python3 installed. Try the following: python3 -m venv .venv - if my assumption is correct this would create the .venv folder inside the directory you're in
this is what i get when i install simplejwt
Requirement already satisfied: pytz in /usr/local/lib/python3.9/site-packages (from django->djangorestframework-simplejwt) (2021.1)
because this is installed in your global
after creating the .venv you need to activate it and then install your dependencies
hmmm i do have venv folder but still got the same error
yo ive been stuck here help me 😅
i am getting the "form is invalid" output on my terminal meaning i failed the form.is_valid check how to debug that?
did you activate it? and then installed there your dependencies?
how do it know why is my form.is_valid() failed?
no ive not activated it ill check how to do it
Might be good to have an else where you do form = CommentForm() so that if your form fail for some reason it will get back to your templates and then your templates should render the errors
You can run source .venv/bin/activate
like this?
but how do i print errors? is in on templates? or terminal?
No, the else should be in the same level as the first if
the if request.method == 'POST'
bash: .venv/bin/activate: No such file or directory
can we go to a video room so that you can share your screen?
I'm in Live-Coding
this?
but it will only run if i dont have request.method = 'POST' right?
how will the else statement be triggered? was it if my form is not valid?
yes is der not an extension for that
i think u can only do that for html and css
if your form is not valid it won't pass to the else and will go directly be passed to the context variable
can you run then ls -la in your current dir and show here the results?
ill send in private chat
then what is the reason for the else statement? 😅 sorry i just dont get the flow of what i am doing now im confused hahaha
the else statement is basically saying: if this is not a POST method, let's instantiate an empty form and send it to the context to be rendered in the template
oh right i get it now i see
but i still got my main problem my form is invalid
this is my model
and this is my modelform
since user and news_id should be automaticall filled based on the id and currently logged in user i filled it on view by the initial={} argument and the only thing i am getting on the form is the comment field
i feel like this is a simple problem with simple solution but i still cant figure it out im at dark with this django hahaha😅
I think then the problem is that you're creating two different forms at once. The correct approach would be: form = CommentForm(request.POST, initials={"user_id": user.id, "news_id": news.id})
yeah youre right
i did your revision but i still get the form is invalid output on my terminal means i failed the form.is_valid() check
Try adding a breakpoint() before the form.is_valid() line. When the code hits this point it will stop the server there. Then you will be able to see what is happening by printing the values
i used the first answer here and now i am seeing this error messages on my terminal https://stackoverflow.com/questions/20723646/form-is-valid-returns-false-django
When the server stops there you can do the following:
yes how can i check form values?
print(form.is_valid())
print(form.errors)
it will show you what are the errors in your forms
there it is my form are empty
but when i print the news and user variables i got values of them
or do i need the ids? because they are foriegn keys?
yes you don't pass the object, you need to pass the IDs
its the same even i pass the ids on the forms same form.errors
this is how the code looks like now
btw how do i stop that breakpoint()?
to stop it or just go you press c and enter
oh i got it nice this is a handy tool e h
anyways back to my horror story
why is my forms becoming empty? the code shows that they have values but they are infact empty
yeah I'm a little bit confused 🤔
can you run again and then print the value of request.POST?
const getData = new XMLHttpRequest
getData.open("GET","https://api.ipify.org?format=json");
getData.send();
ipData = getData.responseType = 'json';
document.getElementById("tag1").innerHTML = ipData
umm anyone know why this wont work
im a bit new to requests in javascript so
i am getting the comment value on post
haha what is happening here am i hunted? 
You need to read the response in a callback.
and call the constructor. new XMLHttpRequest()
though you should prefer using the fetch api
function onSuccess() {
document.getElementById("tag1").innerHTML = this.responseText
}
const xhr = new XMLHttpRequest()
xhr.addEventListener("load", onSuccess);
xhr.open("GET", ...)
xhr.send()
// vs
fetch(...)
.then((data) => data.text())
.then((data) => {
document.getElementById("tag1").innerHTML = data
})
can you also show your templates as well?
actually that now I'm seeing your model you really should pass the objects not the ids form = CommentForm(request.POST, initials={"user_id": user, "news_id": news})
here is my template simple render of the form
I think you should have something like {{ commentForm.as_p }} because the way it is right now you're only rendering one field: the comment
but it shows the fields that should be hidden and filled automatically
Hmmm so I think you should update your model form to make those fields rendered and then continue to pass the initial to then. Check here: https://stackoverflow.com/a/23463004/3716354
you mean the widgets?
btw is this a correct approach? or there is a better way to get this comment from user?
if you have fields that you don't want to show to the user in the form, you have either two options:
- override these fields in your
ModelFormand make them not required. Then pass the values from the initial option (you might need to also override the ModelForm__init__to set these values. With this when you submit the form again your form won't complain saying that some fields are missing - In your form you use the widget approach to make them hidden so that only the comment field will appear in the frontend and then set the initial values in your form
In lodash, is there a shorthand for this? ```js
_.map(x, (id) => object[id])
I managed to do _.partial(_.get, object)
do have link for example on option 1?
also on option 2 is it safe like the hidden fields are hidden even on htmL? you know thos inspect element stuff
You can see some examples here: https://docs.djangoproject.com/en/4.0/ref/forms/fields/#core-field-arguments for option 1
Following with something like this https://stackoverflow.com/a/604325/3716354 and something like this to set the default values: https://stackoverflow.com/a/51162353/3716354
i think this option 1 is a more appropriate way of doing things?
Probably, yes
widget thing can be altered on html by browser
but i dont understand this option one haha imma rest for now see you again next time sir thank you @novel stream
How to make migrations in Django after deleting the migrations and pycache dirs and after flushing the db? Tried migrate and makemigrations and it keeps saying nothing to do
Goddamnit, why it has to be always so rtarded in django with all the migrations stuff
hmm, so you did everything described in Scenario 1 here?: https://simpleisbetterthancomplex.com/tutorial/2016/07/26/how-to-reset-migrations.html
Yeah, and I'm back to where I was before deleting those dirs, now i got this annoying err ```
File "C:\Users\ansga\Desktop\SHOP2\django\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such column: store_product.safe_name
So its like I got this in my models, but migrations are not following it, and there is no such record in db yet, weird thing
Oh, my model was bad, I've noticed it after fixing manually the migrations that I'm putting the raw bytes into a CharField, I'm dumb, move along nothing happened here
hi guys, I'm using SQLAlchemy and I'm trying to delete a row after it's been updated like so:
@event.listens_for(Emails, 'after_update')
def delete_retrieved_email(mapper, connection, target):
# If email row has been retrieved, it has been saved in the client's local storage. We now delete it off the server.
if target.retrieved:
with Session(engine) as session_:
session_.delete(target)
session_.commit()
The issue is that the row is not being deleted. Any help please?
What's the difference between:
class customUser(AbstractUser):
pass
and
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
?
The former is meant to be a replacement of the user model, so that setting needs to be updated, and it will require a potentially difficult migration if you're not doing this at the start of your project.
The latter creates a separate table with a FK to the user table
At a higher level, I think the choice comes down to a semantic difference.
Like, if you have data associated with a user that's only relevant/useful in certain contexts, then the OneToOne approach may be more suited to that.
Though when you start your project, it's good practice anyway to subclass AbstractUser and create a custom user model (in case you need it in the future)
how to add two numbers in js and show output in different page?
n + n where n is a valid number, as for as "show output in a different page", I have no idea what you mean by that
There's also a dedicated JavaScript Discord considering this isn't really related to Python at all in any way https://discord.com/invite/dAF4F28
Oh, you said it's a Django project in #python-discussion, nevermind
can someone explain why im getting this error when i have the package installed => from .utils import generate_access_token ModuleNotFoundError: No module named 'Occupier.utils'
Hi. Show project files tree
if user has downloaded css from a cdn and cached it, will the browser also detect if the same css is given locally?
and load the cached one?
hi, Is this the correct way to include the csrf_token in JS using fetch?
const csrftoken = document.querySelector('input[name=csrfmiddlewaretoken]').value
fetch(likeUrl, {
method: "PUT",
headers: {
'X-CSRFToken': csrftoken
},
...
is django just a debugger or full website builder? i mean i need to know html/css or just python?
probably yes. the project that serves the css from the CDN usually also serves it with a key by the end so that when a new one is created the browser will invalidate the cache and retrieve the new CSS file instead of the old one
Yes, Django is a full web framework to build websites and full websystems. You will need to know some HTML/CSS for sure if you plan to work with Django. Now if you plan to work with APIs you kinda can skip HTML/CSS but some basic knowledge about it is totally worth it
i plan to make a subdomain thingy for my website that is linked with my linux machine which will run a hardware info/usage monitor script and website will fetch these
hoping i can achieve a live update of these lol
Hey guys! I am trying to use Mongo db in my django project using djongo. But I am getting "int() argument must be a string, a bytes-like object or a number, not 'ObjectId'" on rest model serializes when POST resource. i have refereed many resources online but it doesn't mention an issue like this. guys give me some insights on this. i have tried to add an _id field with ObjectId field type from djongo. but with that solution i can create resources in POST but can't get resource using _id or id field. did anyone face this issue before? how do i fix it? have any useful resources ? if have please share. thanks
bit confused how can i do that ?
If you have linux, run tree in main dir of project. Or just screen files explorer in your IDE
ok i will send a screenshot
im working on my frist django project ```py
q = Question(question_text="What's new?", pub_date=timezone.now())
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\HP\Desktop\DAMINDU\my-site\venv\lib\site-packages\django\db\models\base.py", line 559, in init
raise TypeError(
TypeError: Question() got an unexpected keyword argument 'question_text'
anyone know why this coming? help please 🥺
Where is your utils file?
how's your Question model?
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
def __str__(self):
return self.choice_text
well, your question is empty there's no fields in it. I think you're following the official Django tutorial, so keep reading there
Django Question:
I want to pass a search via a search bar of: dog, blue, tall
That will look up all tall, blue dogs in my database.
qs = qs.filter(dog__icontains=dog_contains_query)
only allows me to look up one parameter at a time, and will return all results with dog, bu tif I have dog, blue, will look for a match of dog,blue, and will return nothing.
So far ive given heavy consideration to AND as well as OR, and have even considered UNION, but I dont know if union would work, or even how to get it to work, and Im not sure what security flaws it may introduce, but Im pretty sure its not as bad as: raw() Execute a raw SQL statement
i also tried this, which it shows very promising results, but I had to add this to the URL directly, vs using the search bar
Finally complete my project
I'm a django beginner give me some feedback
could anyone help me out ? #help-chocolate message
data = User.objects.all().annotate(user=Count('bid')).aggregate(max=Max('user')) i want get user which has the most bids currently. i get number of bids {'max'2} but i don't understand how to get id of this user
im trying to set up django with react to create a little project. im tying to load in an html file and django doesnt find it because the source its looking for is wrong, can someone tell me how to rewrite the base url so it can find the files correctly? my project is in a dir containing the django file, a venv and the react files in it
Is it smart to use any python backend framework with an javascript frontend framework for example react with flask?
anyone know what the default timeout length for a flask request is?
Flask by itself doesn't have a timeout length. I think that's handled by the web server layer, one/two layers up
https://discuss.python.org/t/flask-request-timeouts/10734
yeah thats kinda what I figured, thanks
Hey can someone please help me in #help-bagel, it has to do with Flask and a Chat Apps formatting issues.
@pallid hill For some reason I can't type in the help channel. I didnt read your code because I'm on mobile at the moment but based on what your asking for i think overflow-x or overflow-y would solve your problem. Heres a good reference: https://www.w3schools.com/CSSref/css3_pr_overflow-x.asp
I've seen a number of web devs speak highly of Django and React. I haven't gone there yet, but the reasons-for presented have made sense.
And so, as for how smart this practice is likely a case-by-case situation. I haven't used React because the problems I've focused on have been functional-centric. However, I hear very good things in terms of managing front-end behaviour. React also appears to have a decent collection of libraries and an active community.
What I wonder about is that Flask is a fairly straightforward web dev framework. You can build out a lot of functionality, but one doesn't have to wander too far along the spectrum before Django presents good reasons to be used over Flask. I would be curious to learn about use-cases for Flask+React.
That's a HUGE question 😄 But I understand. I'll offer reflections from 10 minutes quickly scanning the github:
- **bike **is an interesting project name for a web app selling cars 🙂
- settings.py > brush up on environment variables, and secure all KEYS. SECRET_KEY should be changed, and hidden within an env var.
-** use of sqlite3 **> If you're serious about Django, read up on other DBs, such as PostgreSQL. - **MEDIA **on a django server is fine for small projects. If you plan to go production with a web app storing uploaded media files I'd brush up on other ways to do that. When you include Media on your Django app it is no longer stateless (Load balancing issues if project takes off) and there are security risks that come with file uploads
- naming of home app > I've not taken that approach. I name my apps based on their functional focus. The functional focus of home is...the home page? Looking at home.views.py very quickly reveals that this is the main car app. Perhaps car_sales_engine or something like that might be more descriptive. This is a minor detail, but when you're expanding your coding chops with projects containing more than 3 to 4 apps how you name apps is going to make a difference long term...
I'll stop there. That was the first 10 minutes. I hope that helps. Good luck. Love the energy and the movement towards full-stack dev.
Book I recommend: https://www.feldroy.com/books/two-scoops-of-django-3-x
Feldroy is a small indie publisher of technical and fiction books.
I tried to add that in css but for some reason it does nothing, maybe some deeper implementation is needed, although I’m really not all to sure.
HTML Jinja templates are great for what they are, so it depends on your requirements. If you want to build an SPA or in general a very dynamic front-end, then I would a say a framework like React is the smart thing to do.
Thanks man for honest feedback!
I will read this book
@native tide It doesn't scroll once so ever, but I have no idea why this is.
Instead it just resizes the box and scrolls the whole page in that process. Please help.
hi, for my current project im using the html data attribute quite alot but im very concerned about the security of the website because anyone can change the values of the data attributes in the developer tools. how can i protect against this?
is there a way to hide them or something
Thanks guys for the answer @ionic raft @proper hinge
Hello9 i am having issue
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href={{url_for('static', filename='style.css')}} />
<title>Document</title>
</head>
<body>
<h1>Crypto Currency, create your own!</h1>
<form onclick="on_action" method="post">
<form>
<center><p>Name: </p><input class="inputtype" name="name" type="text" /></center>
<br/>
<input type="submit"/>
</form>
<p>{{name}}</p>
</body>
</html>
index.html
from flask import Flask, render_template, request
app = Flask("__app__", static_folder="static")
@app.route('/', methods=["POST", "GET"])
def on_start():
return render_template("index.html")
@app.route("/on_action", methods=["POST", "GET"])
def take_action():
if request.method == ["POST", "GET"]:
yourname = request.form["name"]
return render_template("index.html", name=yourname)
if __name__ == '__main__':
app.run(debug=True)```
can anyone tell why I can't see {{name}} after clicking submit?
onclick function is different, I see
what?
<form onclick="on_action" method="post"> to <form onclick="take_action" method="post">
its been ages i have used flask. can you check that?
oh yeah i am stupid lol
Has anyone used pythonanywhere before?
been there man! i still make those types of mistakes
🙂
hey could use a bit of help im getting this error => Import "rest_framework_jwt.views" could not be resolved , "generics" is not defined, response" is not defined my requirements.txt => asgiref==3.5.2 backports.zoneinfo==0.2.1 certifi==2022.6.15 charset-normalizer==2.0.12 Django==3.2 django-cors-headers==3.13.0 djangorestframework==3.13.1 djangorestframework-jwt==1.11.0 djangorestframework-simplejwt==5.2.0 idna==3.3 psycopg2-binary==2.9.3 PyJWT==1.7.1 pytz==2022.1 requests==2.28.0 sqlparse==0.4.2 urllib3==1.26.9
Is there any way to get better logging from FastAPI? I have an endpoint that receives a fairly complex JSON object (a push webhook from GitHub) and sometimes my server just logs 422 Unprocessable Entity and nothing else. This would indicate that the data could not be deserialized into an instance of my Python class, but the error isn't exactly helpful in tracking down what it is.
Oh darn. I've googled this several times in the past, but now I stumbled upon the docs for how to handle errors. Never seen them before, so no wonder it's been a bit hard.
Basically I seem to want:
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
exc_str = f'{exc}'.replace('\n', ' ').replace(' ', ' ')
logging.error(f"{request}: {exc_str}")
content = {'status_code': 10422, 'message': exc_str, 'data': None}
return JSONResponse(content=content, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY)
Let's deploy that and see.
Yo guys, as web developers do you learn Wordpress or do you think it could be beneficial to learn WP
They are the same?
Does anyone know why I can't set my chrome window height any larger than 1331px with selenium? It works fine with Firefox
from selenium import webdriver
firefox = webdriver.Firefox()
chrome = webdriver.Chrome()
firefox.set_window_size(1200, 2000)
print(firefox.get_window_size()) # {'width': 1200, 'height': 2000}
chrome.set_window_size(1200, 2000)
print(chrome.get_window_size()) # {'width': 1200, 'height': 1331}
edit: It does work if I start chrome with the --headless argument, but that will cause problems elsewhere.
Did you makemigration and migrate
I'm getting a error from ASGI when I visit the page, how do I fix this?
I'm using FastAPI, and this error seems internal...
Error:
INFO: 127.0.0.1:53735 - "GET /static/styles.css HTTP/1.1" 500 Internal Server Error
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/uvicorn/protocols/http/httptools_impl.py", line 401, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__
return await self.app(scope, receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/fastapi/applications.py", line 269, in __call__
await super().__call__(scope, receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/starlette/applications.py", line 124, in __call__
await self.middleware_stack(scope, receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/starlette/middleware/errors.py", line 184, in __call__
raise exc
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/starlette/middleware/errors.py", line 162, in __call__
await self.app(scope, receive, _send)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/starlette/middleware/base.py", line 69, in __call__
await response(scope, receive, send)
TypeError: 'tuple' object is not callable
no need to they worked perfectly fine before but i get an error when i migrate
If you've looked in django jwt page on requirement section it says that this library for django 1.8 and earlier
yh i saw that then i did the right install cause im using Django==3.2
Right install? I didn't get it
oh like its the up to date version
hey guys
so a group of friends and i wanna set up this website for us that basically holds world cup score predictions and automatically scores points for correct guesses in a leaderboard type of formatt
i would like your advice on where to learn to do this and what video tutorials i should look up 🙂
thanks
When running the following process_view inside middle ware, it's recording two visiting, not sure why https://dpaste.org/pgVcQ
This actually only appears to happen on certain pages.
I'm not sure whether this is the proper place to raise this question. Actually I'm trying to use flask backend to implement sign in with Apple, but I receive this error on running my script.
Could someone please assist me?
headers = {
'kid': AppleApiProvider.KID,
"alg": "RS256"
}
now = datetime.datetime.utcnow()
date = datetime.datetime(now.year, now.month, now.day, 0, 0, 0)
exp_date = date + datetime.timedelta(weeks=8)
payload = {
'iss': AppleApiProvider.ISS,
'iat': date,
'exp': exp_date,
'aud': 'https://appleid.apple.com',
'sub': 'com.APP.staging.signin',
}
client_secret = jwt.encode(
payload,
AppleApiProvider.PRIVATE_KEY,
# algorithm='ES256',
algorithm = "RS256",
headers=headers
).decode("utf-8")
return 'com.APP.staging.signin', client_secret
remind me what does model.manager() does?
TLDR; If you have time it won't hurt. Learning WP on your journey into web development can give you access to a *swiss army knife * web dev toolkit.
On my journey of becoming a web dev I started with WP. It has solid use cases, and some great solutions can emerge. It has a really broad community and plug in options to extend functionality. Is it beneficial to learn WP? That really depends on the use cases you're developing for.
However, WP comes down to how big the compromise needs to be to deliver on use cases and requirements. The three most pressing limitations for me were: 1. it is based on a framework that can make changes that can break your solution (WP Core - beyond your control). 2: It comes with performance overhead because it trying to be many things to many people. 3: Any changes to plugin functionality can also break the application (beyond your control). These limitations come down to a trade off of pros and cons. And perhaps the greatest one is that because WP is so popular as a CMS (Content Mgmt System) it comes with known vulnerabilities, attack vectors, that are rampantly exploited.
I found myself drawn to Python-Django because I wanted a much greater level of control for developing web applications on all three layers (DB, Application and Front-end). Understanding both WP and Django helps me qualify which use cases are better suited to which stack.
Good luck.
Interesting. I'd start by getting really clear on what I want to accomplish:
- It sounds like you will need user account functionality. Users will make their predictions and be scored based on the variance between their prediction and what happens. You want data related to users to persist and always be available. Needs will evolve as you delve into the user's experience and what you're trying to accomplish (such as leaderboards for world cups every 4 years)
- You will need login, logout and password reset functionality.
- You need to design a data model along with what the web application will do (application logic)
- You will also need to determine how you want to front end (the web pages themselves) to present and support this experience.
- That then informs how to design the data model, application logic and web page layout
On one hand, Flask is simpler to get started (for your first project). But based on the real need for account login, Django may end up saving you time overall (it's more complex to learn, but it has built in tools for things like administration and user-authentication).
Advice on where to learn how to do this really depends on how technically comfortable you are with Python and coding in general. I recommend Corey Schafer's YouTube tutorials for both Flask and Django. I spent about 1.5 months learning Flask before I shifted to Django because the projects I build are complex. However, that time with Flask introduced me to web development fundamentals that served me well when stepping up to Django (where I got the bells and whistles). I only code Django web apps now.
this is very helpful.
thank you so much
ill get started with tutorials then
Welcome to the journey into web application development. I started with an idea to build a web app to store information and automation steps for the process improvement methodology I train businesses on. Having a clear idea to drive your development is VERY helpful. Do you have much experience with Python?
mainly my experience comes initially being a mechanical engineer and working with matlab mostly. once i started learning about ai and machine learning i got interested in data science so i got started with python. this world cup prediction website i wanna try to build is just a fun project i thought of but hopefully can develop into experience in django or flask
that will be helpful. You likely have a number of programming concepts down in Python. However, you might be well served by taking a deeper dive into something like a python web dev boot camp. You will use libraries with Django (as you have with matlab for example). And you will lean heavily into many Python programming concepts. Your grasp of programming logic patterns will be helpful too.
And yes, I'm on my third deployed project now (my profile has a couple of links). Building a fun project on an idea you really get is a fantastic way to get experience.
At a guess you're going to find Django very compelling to meet your requirements thoroughly. User authentication in Django is top-notch. In Flask you have to do a lot more heavy lifting.
Disclaimer: I am a HUGE fanboi of Django. I think it's an astonishingly good framework to build a web app on.
hopefully i can easily understand some of the new concepts that django might bring haha
how would it compare to js?
Django is built on Python.
You'll use Python to build the data model (tables and relationships in the DB), and the application logic (the views that get things done). You'll use html to structure web pages, css to style web pages and Django's implementation of Jinja to build those web pages by the web server. And you'll find js will help you with managing web page behaviour. I use js sparingly (because browser based computation is slower than back-end server computation). You will have the option to delve into using a js framework (such as React) to make the most of sophisticated behaviour functionality built to solve front-end requirements.
this is very informative and good to keep in mind going forward
thank you for sharing
Good luck bruh. I LOVE developing web apps in Django. I've had a LOT of fun over the past year or so
getting this error anyone know why => return [auth() for auth in self.authentication_classes] TypeError: 'type' object is not iterable my code => ```class OccupierLoginView(APIView):
serializer_class = LoginSerializer
authentication_classes = (TokenAuthentication)
permission_classes = (AllowAny)
def post(self,request):
username = request.data.get('username',None)
occupier_password = request.data.get('password',None)
if not occupier_password:
raise AuthenticationFailed('A password is needed')
if not username:
raise AuthenticationFailed('A username is needed')
occupier_instance = authenticate(username,password=occupier_password)
if not occupier_instance:
raise AuthenticationFailed('occupier not found')
if occupier_instance.is_active:
occupier_access_token = generate_access_token(occupier_instance)
response = Response()
response.set_cookie(key='access_token',value=occupier_access_token,httponly=True)
response.data = {
'access_token':occupier_access_token
}
return response
return Response({
'message': 'something went wrong'
})````
authentification_classes is not an iterator. (TokenAuthentication) is not a tuple, the parenthesis are just removed. If you want to make a 1-element tuple you need to add a coma after the value, like so: (TokenAuthentication,)
oh thanks it worked
Hello everyone here ! I tried multiple times to install django and djangorestframework from pip3 on my environment on PyCharm, but it's not working at all. When in my installed apps I'm adding 'rest_framework', i'm having an error : ModuleNotFoundError: No module named 'rest_framework'.
Everything I tried didn't work. With "pip freeze" I got this :
asgiref==3.5.2
Django==4.0.5
djangorestframework==3.13.1
pytz==2022.1
sqlparse==0.4.2
tzdata==2022.1
Do you have an idea about what is happening ? Thanks 😦
(In my venv/lib/site-packages I have a folder called 'rest_framework')
can anyone help me my html image wont load
<!DOCTYPE html>
<html lang="eng">
<head>
<title>Image</title>
</head>
<body>
<img src="file:///C:/Users/####/OneDrive/Pictures/85246.jpg" alt="85246.jpg">
</body>
</html>
what is the best way to automate a task of deleting reports on a website
would selenium be good for that?
Hello. I have a discord bot that uses a web scraper. Recently the website we use decided it would like to confuse us all by randomizing the class we draw from? What is the best way to have a wildcard or something for the class. My part of my bot looks something like this currently.
answerBody = soup.find(class_="answer-given-body")
However now they have the classes like this
class = "styled__QnaHtmlContent-oj1dsq-41 duUzTZ"
where those last digits are random based on the particular page.
Hello everyone, I started learning microservices and currently I'm using FastAPI, to implement it I should with Celery package?
Hi everyone,
We are planning on developing an app which will have a facial recognition aspect and some machine learning aspects. This is a senior design project for our class so none of us are exactly experts. But we are trying!
I have done many ML projects but never an app using python. Our professor suggested using Flutter as its cross platform. But from what I am reading it may not be the best option for python APIs.
Could you let me know what your thoughts are for mobile development what should we use if we are decided on python APIs already?
does anyone see anything i try to run it and i get "occupier not found" => ```class OccupierLoginView(APIView):
serializer_class = LoginSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = (AllowAny,)
def post(self,request):
email = request.data.get('email',None)
occupier_password = request.data.get('password',None)
if not occupier_password:
raise AuthenticationFailed('A password is needed')
if not email:
raise AuthenticationFailed('An email is needed')
occupier_instance = authenticate(username=email,password=occupier_password)
if not occupier_instance:
raise AuthenticationFailed('occupier not found')
if occupier_instance.is_active:
occupier_access_token = generate_access_token(occupier_instance)
response = Response()
response.set_cookie(key='access_token',value=occupier_access_token,httponly=True)
response.data = {
'access_token':occupier_access_token
}
return response
return Response({
'message': 'something went wrong'
})```
You probably need to switch your IDE from working with global env to your local venv
Windows paths aren't meant to work in html, use Linux like paths... And give a reading to Head First CSS book, it will teach you the way
It will not matter for your Backend what u will choose for frontend.
Backend will just give away data in Json format / or web sockets in same way as any other backend
Choosing Frontend (mobile one) is usually best in the most compatible option with provided ecosystem. If u use Kotlin for Android, and Swift for iOS, u should be fine.
About framework details I don't know
Is it possible to reuse html filenames when using multiple blueprints?
Eg. I have Homepage blueprint and admin page blueprint, with their appropriate /templates directories. Is it possible to have index.html in both directories?
Right now, for some reason the admin blueprint always loads in the index from homepage
are u sure your view for the admin is correct ?
because both app are different
Should be. Lemme link u it
In the main file i got
app = Flask(__name__)
app.register_blueprint(main_bp)
app.register_blueprint(login_bp)
app.register_blueprint(admin_bp, url_prefix='/admin')
The home BP is:
main_bp = Blueprint('main_bp', __name__, static_folder=Paths.main_static, template_folder='templates')
@main_bp.route('/home')
@main_bp.route('/')
def home_page():
try:
return render_template('index.html')
except TemplateNotFound:
abort(404)
The admin BP is:
admin_bp = Blueprint('admin_bp', __name__, static_folder=Paths.main_static, template_folder='templates')
@admin_bp.route('/home')
@admin_bp.route('/')
def admin_page():
try:
return render_template('index.html')
except TemplateNotFound:
abort(404)
When i go to http://127.0.0.1:5000/ i get the usual homepage, and when i go to http://127.0.0.1:5000/admin/ i still get the same home page
where is /admin route ?
Wdym by that?
is
@admin_bp.route('/admin') not required ?
If i change the admin index to index2 or whatever else, it works fine.
what is a complexity/logic limit on an api-endpoint from a performance/reusability . I'm asking because one of my endpoints is doing about 3-4 things. Should endpoints follow the same principle as functions for example functions should do one thing or 2.
difficult question - if you tell us what 3 - 4 things your endpoint is doing, it'd be easier to tell whether it makes sense
Thank you 🙏
guys literally tell me what are the things and skills needed for making and publishing a portfolio website
i know the html and css part
do i need aws or heruko?
do i beed mango dbl
or sql
Firstly decide if you wish being frontend, backend dev or devops engineer, then we can answer that
https://roadmap.sh/ check the roads there, and decide for yourself
the backend road is awfully missing a lot of things though
no i need .com domian
portfolio doesn't take backend work
https://github.com/darklab8/darklab_backend_roadmap
i tried to draw how backend road looks like better... all the additional green SWE stuff
so, if you build portfolio web site, you are supposedly going into direction of being frontend (or even worse, full stack xD)
besides html and css, you are supposed to know javascript first then, and frontend framework like react or vue.js or angular
you will need something to host it definitely. Anything that you wish fill it. Even github pages can host a staticly built website. So kind of you can go without aws/heroku
mongo db is for backend path. if you wish to build a cool server side stuff, and having frontend is just secondary/non important thing for you, then mongo can be important, otherwise not. Although as average tool, we all use SQL database first. fifty shades of NoSQL databases come later after that, once you understood what for SQL and when could be needed no SQL
yeah realated database and un related database
so what i need is angular and Javascript
i didn't get the part where u said github
can it host a website?
what will the domain in that case
github can host static sites. The domain will be yourname.github.io
If the website is without backend. Only having html/CSS/js. Then it can be hosted on GitHub. It will auto generate domain for u
You can also configure a CNAME to use your own domain
can i change the domain and do i need to pay for service
note: changing the domain means you won't get free ssl/tls
like .com?
yes, but you have to own it
10 cents lol
own the website that i make
SSL will be free anyway, if he would use Cloudflare.... Or letsencrypt
own the domain from a broker.
No point in paid certs
free as in effort
Cloudflare is no effort
You don't need Cloudflare for TLS on Github pages
and there's not really any reason to use it
at that point - just use Cloudflare pages
man when a average person visits a website first thing they notice is the domain
so google domain is a good broker ?
Yeah. I use amazon
aws
is there any extra skil required for Github
why go daddy isn't good?
git is a lang?
Cloudflare for the win
Domain and cert are different things
doesn't matter who provides the domain right we just need that .com
Domain matters
Certs are auto provided for free
namecheap isn't?
how much does that cost
what your website melio lemme check it
yup empty
did u do any backend work on that
wow
u didn't do any html or css or any front end at all right
i bet u can't do like 3d stuff and like that
with it
so theres no point in freelancing
anyone can do that right
what do u call this aws and heruko and github server side?
hugo?
aah
alr lets just hope right
what makes me compete with a website generator is that i can think. shortly that will be done as well
i mean client can't think creativity and thats why im there
anyways thank you all very much
Hey! could someone help me out here? Please direct me to the right channel if I'm not in the right place.
I've built an application in flask, and it works perfectly fine in the production flask server.
I'm trying to deploy it using gunicorn. I've setup a gunicorn_config.py file, and I'm running with the command bash sudo gunicorn -w 4 'app.main:create_app(testing = False)
But here it suddenly tells that worker failed to boot, and it appears the reason is ```line 3, in <module>
from flask import Flask, request, render_template, send_file
ModuleNotFoundError: No module named 'flask'
I've run pip list and Flask is available in the environment, pip install flask is showing requirement already satisfied, and I've rechecked to make sure it works on it's own without gunicorn.
Could someone help me figure out how to debug the issue here?
After a very Hard work on a how to pass python list to C function for test and fun ( i create a prime number function in c and using Ctypes I import So file in python ) it take 0.70 second for finding prime number between 0-500K 💪 dame power of C api
Hey who know flask write me in DMS pls!
(I need a help with creating global server, in webhook (local server working)
Unfortunately this:
import numba
import time
@numba.njit(cache=True)
def sieve_python_jit(limit):
is_prime = [True] * limit
is_prime[0] = False
is_prime[1] = False
for d in range(2, int(limit ** 0.5) + 1):
if is_prime[d]:
for n in range(d * d, limit, d):
is_prime[n] = False
return is_prime
start = time.perf_counter()
sieve_python_jit(500_000)
stop = time.perf_counter() - start
print(f"Took {stop * 1000}ms")
Takes about 150ms - 200ms if you include the JIT warmup.
Otherwise it takes about 5ms 😅
😉 Smarter algorithms and numba will get you a long way
No i code in pure C
And import so file
It take about 0.70 milliseconds in C function i imported
like i have a video upload endpoint, it does
- receives multiple video files and iterates through them
- inside the iteration it checks to see if Redis has cached it
- checks to see if the video exists in the db
- saves the file
- compresses the video (takes 5-10 seconds)
- writes to db
- then it dispatches the video to another processing endpoint
and repeat until there are no more videos received from THAT request.
is that too convoluted? or is that okay
is there anyone who can help me in deploying flask app on heroku ?
if you're hosting on flask, make sure you have these 3 requirements
- Procfile
- runtime.txt
- requirements.txt
your procfile
web: python main.py
your runtime.txt
python-3.10.5
and your requirements.txt
Flask==2.0.
Flask_Login==0.5.0
Flask_SQLAlchemy==2.5.1
Werkzeug==2.0.2
```you need these 3 files in order to host on heroku
these 3 files need to be in the root of your project also where the main.py file should be
can anyone help me regarding mongo db
my current issue is TypeError: 'ImmutableMultiDict' object is not callable since i changed request.form.get to just .form (again)
to answer your questions; no, i'm not going to store passwords in plaintext; it's a placeholder for now
When creating a custom user model, is there a difference between these two
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
pass
.
from django.contrib.auth.models import User
class CustomUser(models.Model):
user = models.OneToOneField(User)
?
User is used to extend the already defined user user class,
AbstractUser is used to make a new user class
yo some pal shared me an account with codewithmosh django tutorial was it good? for beginner to job ready?
STATIC_URL = 'static/'
'''
STATICFILES_DIRS= [
os.path.join(BASE_DIR,'static')
]
'''
STATIC_ROOT=os.path.join(BASE_DIR,'static/')```
when i turn off debug
even tho i run collectstatic
even if i add whitenoise
still
it doesnt load static files
i mean wtf
why
This code is not supposed to work at all
Syntax coloration already shows you tips
U use different ways to declare strings
You make part of your code being strings too
No code, just strings
Variables aren't declared, they are part of strings
hello guys anybody worked with transaction here?
A guide for how to ask good questions in our community.
well, ok. I have a problem where I want to display all the transactions that takes place between two people in the order of latest updated time. Basically I want to show how to implement a receipt
What db are you guys using for your stack ?
Django / React.
I usually use jawsdb over postgres for regular django . There’s 101 videos arguing benefits for all of them though
so, JWTs are often used because they are stateless and don't need storing on the db. But, refresh tokens have to be stored on the db no? so JWTs are not really stateless?
It depends on your implemention
If u use JWT with validating it by secret key and not using dB request. Then it is without dB
JWT can contain additional token that is stored in dB, that can be deleted
Then it will require dB
We have a free reign for everything
Although in second case usually JWT is not used I think. We can transmit directly token in cookie without JWT that we will verify in dB
I think it is called Session token/Auth or something
The point of JWT is technically zero, if we already use session token
So let's consider JWT as thing only without db
Or wait
We can combine both
Let's have JWT storing session token
If JWT is not expired, then allowing request
If time expired or more sensitive request, then verifying session token
sure, but if I'm wrong, people look to use JWTs over sessions so they don't have to store the tokens in the db. There would be no reason to use JWTs + session cookies for that reason
but learning about JWTs and refresh tokens I thought that the refresh tokens had to be stored in the database
but I suppose they do not have to be
can make the refresh tokens JWTs made from my secret key, and some user info (e.g. user_uuid) to make the refresh token specific to that user
so no tokens have to be stored in the db, that's great 👍
so a refresh token is just a JWT with a longer expiry date?
hey, i need help with pyscript is this the correct channel?
is it possible to run a ascii game in pyscript?
like i made hangman
and i would like for there to be some terminal where i can run the game where the user can enter input and whatever else i need to
ping me when you reply. thanks a lot
Anyone familiar with Chameleon templates? I'm trying to fill a table using multiple lists, but I can't seem to figure it out. Details are on Stack Overflow: https://stackoverflow.com/questions/72840828/iterating-over-multiple-lists-in-a-table-in-chameleon
Jwt is access and refresh .
I store mine in local storage which isn’t best practice , but it works for what I need
I am using flask with this code:
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True, port=8000)```
```html
<form method="GET">
<p>Phone number:</p>
<input name="phone_number" type="number">
<br><br>
<input type="submit">
</form>```
I want to be able to use the inputed phone number text as a variable in my python code when it is submitted. How do I do that?
you need to make a POST route
i.e. @app.route("/", methods=["POST"]) then use the request.form variable to get the post data
actually, you're already using get, so you can just do request.form
Also, use the tel type for the input.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/tel
Hello, I'm a little stuck on the Django framework. I have a mockup (a form in my templates) that a user dynamically creates by clicking a (+). The problem is that I don't know how to recover its data.
Any ideas on solving this error :
Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Tech stack :
web server (reverse proxy) : nginx , application : django , application server : gunicorn & Docker.
It is not realted to web development in anyway. Better to tell it in #algos-and-data-structs
well, and mind the language
mimimi
what are some good tools to develop a website quiet fast
im using webflow for the frontend
but it feels like it would be a pain to link the frontend with a django framework
hey guys - I've got a set-cookie header in my response but it's really bugging me that the cookie isn't being set. (doesn't show up in devtools)
set-cookie: access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmYmJkY2EyNWEwMTk0NmFiYTkxM2MzOWI5MTliNzRkYyIsImV4cCI6MTY1Njg4NzY2NH0._v2dp5VMC0CSLSuc8b1IUKqCJn2rSP_o_eL8pQp9a34; Path=/; SameSite=lax
is there any reason as to why this won't show up in devtools? it's in the response, just not being set in the browser!
Vue.js with CSS framework like bootstrap? 🤔
im tryna use django
Or even just rendering in Django templating language
Vue.js connects well with any backend framework (like Django)
oh rly
Sure.
Vue.js + Axios requests to Django Rest Framework endpoints in json format
and voila
Tbh, you can even statically link-insert Vue.js into being rendered from Django templating language 🤔
but that's a pervert way. Better linking in a normal way
Imagine nginx web server
im not good with websites jsut fyi
It just gives away your statically compiled vue.js web site to user
It is at his client side in browser
There(from user browser) u can make http requests with Axios, in GET/POST and etc way to your hosted Django application
Django application in a simple Rest API way accepts JSON inputs and answers results in JSON too
does react work well with django?
Hello guys, assume I am a web developer for 2 years , how long can take me to learn WordPress?
No difference
Except learning curve of react more complicated than Vue.js
Thanks for answering. I have 2 more questions.
- Once I make a new user class(using abstractuser), does it automatically override the existing user class to be considered as the user class for the project?
- Is there a big difference between the extending the pre-defined user class or creating our own user class in terms of practicality? What's the benefit of one over the other on a website?
When u make a new user class (abstract user) u must specify it in settings (base)
Hmm,
As for the difference subclassing user is done when you are in the middle of the project and want to extend the current user,
Abstract is used when you are starting a new project and want to control everything about the user
So I hosted my flask app in railway.app but in the logs it starts the gunicron worker and it says connection in use it says retrying in 1 sec and then it says cant connect and exits anyone help?
Has anyone worked with whatsapp Webhook and flask
Hi, im tryna deploy my app however im getting a ValueError: Required parameter not ste for the following:
<img src="{{ request.user.profile.picture.url }}" class="rounded-circle" alt="Profile Picture">
i dont understand why im getting this since i have all the environment variables set properly
It's not clear enough! Show the full error.
and maybe the url is returning different result to be ValueError.
the website currently works fine on my local machine however the deployed version doesnt work due to the above error
maybe try user.profile... instead of request.user.profile... 😐
the original was user.profile.... and i was getting the error
i changed it to request.user... to see if it worked but same thing
the user object gave no error! because the user.is_authenticated works fine.
so, the problem should lie inside the user.profile or user.profile.picture or the url of the profile class.
try checking the attributes of the user in your terminal.
before rendering, print the user.profile.picture.url and see if the error is coming from the user.profile attributes.
yes the error is coming from user.profile. I checked it before.
so you need to check the User model. and link the profile model with it, is that part ok?
ye that part works. When i check the admin dashboard everything works fine except my profile model. When i click on a user in the admin dashboard inside the profile model i get the ValueError: Required parameter not set error
im gonna delete all the environment variables and set them again once again lol
ye same shit nothing happened
in flask how can i get the full route with paramaters
ex : /completed?token=xxxxx-x-xx-xx&lang=xx
good morning
someone know where is the sites-available file in windows10-apache2.4?
found ir!!, thanks
Flask. Paths, Saving files.
def write_sample_file(save_to_path):
with open(save_to_path, 'w') as f:
print(f'Saving to path: {save_to_path}')
f.write('Great success')
On route:
root_path = current_app.root_path
instance_path = current_app.instance_path
save_to_path_1 = os.path.join(root_path, 'static', 'sample.txt')
save_to_path_2 = os.path.join(instance_path, 'static', 'sample2.txt')
Second call fails (naturally?!)
But stackoverflow (https://stackoverflow.com/questions/36649703/get-root-path-of-flask-application/36651006#36651006 )insist people use instance path instead of root. WHY? HOW?
root_path: /home/[PCNAME]/Coding/flask_path
instance_path: /home/[PCNAME]/Coding/flask_path/instance
flask docs have:
UPLOAD_FOLDER = '/path/to/the/uploads'
which is not useful and seems like hard-coding path to config.
Can I get selenium help here
Correction to question above: I did not paste calls to functions:
write_sample_file(save_to_path_1)
write_sample_file(save_to_path_2)
second one (using current_app.instance path) - fails,
Hey guys, is it smart for me to rather use client sessions or just return the html file once the user logged in
Hey I got this error in postges sql .. how to solve this ?
Anyone have any links on best practices to interface Discord with Django?
column name should not be enclosed in "
using webhooks ?
I'm not quite sure, I've done it before just using the Discord library living inside an app called discordbot, was a mess.
as django does not fully support async its not generally used to bridge, it would be much better/eaiser if u use FASTApi and such
@worn aurora Thanks, could you provide some material so I can start on the right path? Thanks for the help 🙂
its pretty easy tbh
here is a bot i made a few days back that uses the same thing
https://github.com/battlefield-portal-community/ranger/blob/main/bot/dashboard/dashboard.py
so u do this on global level
app = FastAPI()
discord_client = DiscordOAuthClient(client_id, client_secret, redirect_uri,
scopes=("email", "identify", "guilds"))
dashboard_root = project_base_path / "dashboard"
static_path = dashboard_root / "static"
app.mount(str(static_path), StaticFiles(directory=static_path), name="static")
templates = Jinja2Templates(directory=dashboard_root / "templates")
from bot.bot import Ranger
if os.getenv('DEBUG_SERVER', '').lower() != 'true':
bot = Ranger(debug_guilds=[
int(os.getenv('GUILD_ID'))
])
ensure_defaults() # blocking call
bot.load_custom_cogs()
then
@app.on_event("startup")
async def startup():
logger.debug("Starting Bot....")
if os.getenv('DEBUG_SERVER', '').lower() != 'true':
asyncio.create_task(bot.start(os.getenv("DISCORD_TOKEN")))
else:
logger.debug("Server Debugging turned on... skipping starting bot")
this also has code for Oauth, so u can skip it if u like
template serving in fastapi is a bit slower than django but it makes up for it by making it easy to develop
btw what is your end goal ?
what does it means ?
like this is wrong, look at the where clause
SELECT * from table1
where "column1"="value"
Hey
Does someone know how to get form information with Flask?
I am trying this
<form>
<input type="text" placeholder="Nombre">
<input type="text" placeholder="Apellido/s">
<input type="text" placeholder="DNI/NIE/NIF">
<input type="email" placeholder="Correo electrónico">
<input type="password" placeholder="Contraseña">
<input type="password" placeholder="Confirmar contraseña">
<button>REGISTRARSE</button>
</form>
@app.route("/cliente")
def clientes():
return render_template("cliente.html")
@app.route("/cliente", methods=["POST"])
def clientes_post():
print("ASD")
you need a submit input in the form
and put the attribute method=“POST” on the form tag
you also need to put an id on the form tag to later distinguish it in python
how do I get form answers by form id?
on the function do
if request.method == "POST":
form_information = request.form['form_id']
@app.route("/cliente")
def clientes():
if request.method == "POST":
form_information = request.form['form_id']
return render_template("cliente.html")
@app.route("/cliente", methods=["POST"])
def clientes_post():
print("ASD")
should be here
also youre using the same app routes
that wouldnt work
they all go through the same one
sure
but if you want information to be pulled from the post youd need to use request and access the form
I get an error
what is it
u need to add type hint
ohh flask, i though we were on fastapi
and
you should close the help channel if your asking for help here
is the form on index.html?
you need to move everything and put your if request.method == post there
it's in cliente.html
oh
its
flask.request.method == 'POST' for flask
How much django would one need to know to be able to build a website similar to this? https://www.erepublik.com/ (basically a social network disguised as a "game")
I have the basics of django down(models, fields, databases) but I don't know stuff like property decorators, signals etc. Should I learn those before trying to build a website like this? or can I build it with just knowing the fundamentals
ive done request.method and it works
u can remove the param from the function def
arent what you did flipped? shouldnt it show the cliente html if you did not get a post request
hm
@worn aurora thoughts?
okay glad it works
yeah
now it works
now how to get form inputs
id from form is "register"
hmmm i can't login to the game, so not sure what all is there,
but bare-bones will be
django, db, user management, websockets
as i cant see the acctual game cant really say much
well there's different countries and you join a country, you can start a business, fight in battles where all citizens from one country fight vs all citizens from other country and u just have to press one button to "fight". the whole game is pretty much text-based.
the main thing would just be the same functionality as a social network website(like a really watered down facebook)
ahh then i guess above mentioned things will be enough
How do I get the form inputs?
is there a way to get all of the inputs inside a form at once=
I can manage to get one by one
but not all at a time
Let's say I have a currency model for my application(shown below). the application will have multiple currencies.
How would I go about implementing it so that each user can have a certain quantity of some currencies? and with methods that can increase/decrease currency in someone's account
This is what I've written so far:
class Currency(models.Model):
name = models.CharField(max_length=100)
symbol = models.CharField(max_length=100)
country = models.ForeignKey(Country, on_delete=models.CASCADE, default='')
Should I create a foreignkey field within the user profile? but how would I implement quantity of currency then?
tell me how to host a Quart app, im using Hypercorn but i really dont know how to host it on a specific domain
it says the app is listening on "0.0.0.0:8000" :P
yes
Can I detect where form is being sent?
I have two forms in my web and I wanna know which one is being sent
I need help making a website
I want to have two different sites that are linked together
but im not sure what to use
my main issue is front end
but I'm here to ask if there is something out there that will help me build a digital product store
I've seen webflow but it feels like people can just right click download
and the other site is when i want to upload products then later on package them
Something out there as in only for the frontend, or backend as well? @agile gyro
both
would be nice
its this shit that sketchs me out
i think i will just make a unique link api
the major thing im worried about is how to prevent shared download links
im not sure how to do that
for example i want to be able to send a link for them to download
but they would have to sign in
for it to work
do u think i can do thisin wordpress
I'd assume so as from what I understand, you can do just about anything with wordpress, but I have also never used it so take my word with a grain of salt.
ya ive only heard good things about it never used it either
hey guys I'm trying to learn how to get requests, ur lib to automate stuff on websites. I feel completely ignorant on the topic, does anyone know where should I start to learn the network tab, understand how to make requests etc.. Most of youtube videos just show how to do it but not the actual science behind it so If someone could tell me where to look would be greatly appreciated.
Hey guys i recently created a social networking web application and would love to get some feedback/constructive criticism on it. https://socialfront50.herokuapp.com
My userprofile model has a function to increase the user's experience points by 5.
Is there a way to implement a button on an HTML page so that each time someone clicks that button, their XP goes up by 5(by calling the model method)?
It looks great but it’s pretty slow
Its also perhap scaled a bit too large for mobile
ye im not sure what to do about that, i thought it's because of heroku.
ah fair enough, ill lower the sizes more
it might be slow because of the pictures because i dont resize the pictures since i dont know how to create a lambda function for it
I think if you use a program called fiddler you c a actually generate Python code for a given request
It’s been a while since I used it but I think it’s possible to right click and ask for Python code. It’s basically a proxy that sits between the backend and your browser when you use websites. That could probably help you learn. Also curl
hey could somone help me with this error => django.core.exceptions.ImproperlyConfigured: Field name `token` is not valid for model `Occupier`. my code => ```class Occupier(AbstractBaseUser,PermissionsMixin):
#occupiers can join several cliques
#all posts must go to a specific clique
email = models.EmailField(verbose_name='email',max_length=59, unique=True)
username = models.CharField(max_length=30,unique=True)
occupations = models.CharField(max_length=200,null=False) #amount of occupations user does
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
dob = models.DateField(blank=True, null=True,unique=False)
password = models.CharField(unique=True, max_length=200)
first_name = models.CharField(max_length=200,null=True)
last_name = models.CharField(max_length=200,null=True)
objects = OccupierManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email','occupations','password','dob']
def str_(self):
return self.username
def has_perm(self,perm, obj=None):
return self.is_admin
def has_module_perms(self,app_label):
return True
@property
def token(self):
token = jwt.encode({'username':self.username,'email':self.email,'exp':datetime.utcnow() + timedelta(hours=24)},
settings.SECRET_KEY,
algorithm='HS256' )
return token```
If you read about http verbs that should get you started. The most common are create, read, update, delete (CRUD) The get request is the read one. You can see this in the network tab by clicking Fetch/XHR this filters the list of requests to only show http requests.
So im making a little flask project where i enter a city name in a stringfield and then click on the submit button and then it shows me the weather of that particular city in a html card
the problem im facing is that i am unable to find a way to display the card once the form has been submitted.
i think i shud be using an if statement using jinja templating but i am having a hard time figuring out how to get it working
<body style="background-color:rgb(91, 94, 166);">
<div style="text-align:center; padding:20px;padding-bottom:50px; color: whitesmoke;">
<h1 class="display-3">TheWeatherApp</h1>
</div>
<div style="width: 40%; background-color: whitesmoke;padding: 12px;margin:auto;border-radius:20px;">
<div style="text-align: center">
<div class="col-auto">
<form method="post" action='{{url_for("index")}}'>
{{form.hidden_tag()}}
<h1 class="display-6">Enter City Name</h1>
</div>
<div style="width:70%;margin:auto;padding-bottom:10px;">
{{form.city(class="form-control")}}
</div>
<div class="col-auto">
{{form.submit(class="btn btn-outline-secondary")}}
<!--<button type="submit" class="btn btn-outline-secondary">Search</button>-->
</div>
</form>
</div>
</div>
{% if form.city.data is not none%}
<div class="card" style="width: 18rem;">
<img src="..." class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
{% endif %}
</body>```
heres the html
@app.route("/",methods=['GET','POST'])
def index():
form = CityForm()
if form.validate_on_submit():
print(form.city.data)
return redirect(url_for('index'))
return render_template("index.html",form=form)```
and heres the flask function
any idea why webssh throws these?
Hello, I already tried two times to get help from regular channels so I am trying here. I have this in my function to generate html :
data = """var script = document.createElement("script");..."""
postfix.append(html.script(data))
but then it generate this <script>var script = document.createElement("script");...</script>
How can i handle with this to force to don't escape in my string ?
html come from py.xml import html.
Try to use "
Hey there,
I am converting the MongoDB Cursor() object I get from performing a query in pymongo to a list using the list() operation. This conversion typically takes about 0.5 seconds for only 32 documents that are not very large in size at all. How could I speed up this type conversion?
How do I deply a Flask app (ubuntu server)
I have it deployed but it might be causing conflict with my other website
You probably need to put it behind a reverse proxy such as Nginx or Caddy - or if you already have one, you might need to reconfigure it
It looks like you're running it with the flask dev server - that's usually a bad idea - here's a DigitalOcean article walking you through the whole setup of using Nginx + Gunicorn which I'd suggest trying to apply to your specific app. https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04
ik
I am already looking a video tutorial
before continuing I want to know how to host two websites at the time
once you've set up one app, adding another is fairly easy. I haven't used Nginx in years, I've used Caddy instead, but iirc you just add another location section to your Nginx config
Here's a quick tutorial to setup an Nginx reverse proxy server. This example uses an Apache Tomcat server but the config settings apply for other backend app servers such as Node, Express, ...
the other website is just html css and js
no flask
How to apply css on imagefield in django models ? When I put that in html: img tag, only inline css works, niether internal, nor external.
each field has a auto_id why not use that ?
how do i determine how many vCPUs i need and Ram ?
it is a digital ecommerce store
i think will have 50 active users at once
but at launch would probably have 200+
Everything was correct, there was a problem with indentation in my html file. But still thanks for the answer.
Now it works fine
how can i hide from website that im using chromedriver ?
You can use vim or perl to replace the cdc_ string in chromedriver
ensure that $cdc_ doesn't exists anymore as a document variable
download chromedriver source code, modify chromedriver and re-compile $cdc_ under different name. @autumn veldt
i get an error
look
OSError: [WinError 216] This version of %1 is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher
but it worked before the change
with what name did you changed the $cdc_ ?
you have to make sure that the replacement string (e.g., dog_) has the same number of characters as the search string
$abc_asdjflasutopfhvcZLmcfl_
yeah i know
You have to change the jdk location in project structure
Follow those steps
Go to file -> project structure -> sdk location
Unselect Use embedded jdk(recommended)
Then Change the jdk location to C)Program Files/java/jdk1.x.x_xxx
Where x is dependent on the JDK version you have installed locally.
Hello
A guide for how to ask good questions in our community.
Hey All, I am trying to re-direct a url from a function in views.py, but upon running the api
I get "function at 0xxx14" some mem Location .
I am using return redirect (url) . Can anyone suggest something here .(Django)
https://docs.djangoproject.com/en/4.0/topics/http/shortcuts/#examples this looks like full of examples for django 4.0🤔
Ummm... can't explain properly in text! but you may take a look at this video which I followed for my django tutorial (https://youtu.be/5zNR3E6WRLE?list=PL4cUxeGkcC9ib4HsrXEYpQnTOTZE1x0uc&t=50).
Then it is highly recommended that you read through the docs for sometime and if you have any specific problem understanding some parts, ask here again.
Don't be discouraged to ask.
Django Models Docs: https://docs.djangoproject.com/en/4.0/topics/db/models/
@inland oak Thanks Buddy, I did refer this, wanted to know if we can also call a function in redirect? 🤔
sure, why not? 🤔
I would recommend using reverse url function though
it is always better to reidrect by view name or by
transforming url name into its url https://docs.djangoproject.com/en/4.0/ref/urlresolvers/
Alright , haven't used reverse url, gonna check out the link which you sent. Thanks again
what does https://docs.djangoproject.com/en/4.0/topics/http/shortcuts/#examples do actually? is it kind of manual for python
i want a proper manual for python like the understanding of every code like print(),"",# etc
hey, does anyone know why two sub folders get created inside the project folder if I'd like to make an HTML/CSS file?
blog is the app, but I have a subfolder within templates called blog. Anyone know why? Why would I not just have the html file in templates
Yes
is there a way to change the name of object list inside the admin page of django instead of just object 1, object 2, etc?
Kinda late but this is how Django documentation recommends to do things
It's simply a standard set by Django community and Django framework, made to avoid confusion and some type of future problems
try to add this in your models.py file in your class:
def __str__(self):
return self.****
swap the 4 'stars' with a variable which contains the name of your object
explanation above
Thanks!
Anyone know what a 'OPTIONS' request is?
I am sending an API on iPhone and instead of a POST like my desktop does, it is sending OPTIONS
typically used for a CORS preflight
it gets sent out ahead of CORS enabled requests by your browser
if you control the server - you probably want to handle it
not necessarily writing code to handle it - just respond to the preflight at the reverse proxy level, or with some middleware type thing like Flask-Cors
Okay thank you
Just figured out why it is sending the CORS preflight. It is because I was on HTTP and sending the request to the HTTPS version of my website
is there a way to use python with html
I've made most of my website with html
but I want to add some functions to it that I think I can only do with py
such as selection
how to give permission to certain users to view certain pages?
there is no good way to do it, no. JavaScript is pretty much the only way @native tide
Database no?
Maybe using MySQL
Find the user and set a column "allowed" to True
damn that sucks haha I gotta learn js then
i mean django, what i want is when my user login, they can only view certtain pages.
JS isn't too difficult to pick up. You can either just jump into it with trial and error, or work through a tutorial. The Mozilla tutorial is a little dry but fairly good if you go that way https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps
In our first JavaScript module, we first answer some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing JavaScript. After that, we discuss some key building blocks in detail, such as variables, strings, numbers an...
(I'm not actually 100% sure that's the right Mozilla tutorial, but Mozilla is definitely the place to go to)
so this will basically allow me to add logic based stuff to my website?
if u know what I mean
not just text and pics etc
Yeah
for now, i just do an if statement in the html file that says you cant view this page.
The Django docs has infrastructure to handle permissions.. Have you had the chance to try implementing it?
https://docs.djangoproject.com/en/4.0/topics/auth/default/
hello friend, can i dm you?
im not ready for that level of commitment lol, whats your question?
understandable, Ok so heres my question:
I am building an employer admin program.
Within my user management app, in my models.py file, I have a Profile class pointing to Company class using models.OneToOneField. The company class points to an Employee class via models.ForeignKey.
When I create a company profile and I create a company along with and it works just fine, but when i make more than one employee in relation to the company and works fine, but when I retrieve that employee, I get a just one employee. How can i make it to like whenever i call the employees by doing: obj.company.employee i get all the employees instead of the latest employees saved in the db
heres the models.py file with the models describe above: https://github.com/AngelM512/hr_program/blob/master/userMgt/models.py
i am very new to django so i am very thankful for your help
class Company(models.Model):
name = models.CharField(blank=True, max_length=45)
address = models.CharField(blank=True, max_length=255)
employee = models.ForeignKey(Employee,
on_delete=models.CASCADE,
blank=True,
null=True)
in your company obj you have an employee field, that will have one employee per company or a list of identically named companies with one employee each
is this intentional?
no, i want the company to have many employees but each employee can only work for a company
class Employee(models.Model):
first_name = models.CharField(max_length=20,blank=False)
last_name = models.CharField(max_length=20,blank=False)
prefered_name = models.CharField(max_length=20,blank=True)
birth_date = models.DateField()
gender = models.CharField(max_length=1)
salary = models.IntegerField()
hired_date = models.DateField()
department = models.CharField(max_length=45)
company = models.Foreignkey(Company, on_delete=models.Cascade, blank=True, null=True)
def __str__(self) -> str:
return (self.first_name +' '+ self.last_name)
add the company as a foreignkey to the employee model
remove the employee field from the company
obj = Employee.objects.filter(company='put company id here').all()
then you can query your employees like this
then obj will be an array of all employees with specific company
dude you are the best thank you so much. program is working the way i want it now
@daring isle
No worries bro , good luck with the rest 🤟🏽
django.db.utils.OperationalError: (2006, 'SSL connection error: unknown error number') I got this error when I try to migrate my database to mysql. I've looked up the internet and found no solution. Can anyone help me?
nvm, i use posgresql now
Hey who know flask web hooks write me in DMS pls!
I need help.
https://github.com/fiduswriter/Simple-DataTables
How do I use this in flask without CDN and without NPM?
I tried something like this :
<script type="module">
import {DataTable} from "./static/datatable/datatable.js"
const myTable = document.querySelector("#myTable");
const dataTable = new DataTable(myTable);
</script>
Does not seem to work. Please help!
How do you change width of image in a carousel?
Hi,
What library do you recommend for rest api?
Exactly what framework is usually used for large commercial projects?
I would like to learn a framework that I can use in the future at work
I prefer Express.js for that. To me it's easily learnable, adaptable and it is widely used. [only my opinion]
Fast API (considered best)
Django Rest Framework (considered best/or good... ergh it has its own strengths to provide uniform enviroment for any dev and blazingly fast development)
CAN I GET A REPLY HERE IAM NEW HERE BTW....HI!
requests
But, this library is for node.js
I used this and know how it work
Thanks, I will check it
from bs4 import BeautifulSoup
import requests
url = "https://www.hertzcarsales.com/used-cars-for-sale.htm?geoZip=73301&geoRadius=0"
page = requests.get(url)
soup = BeautifulSoup(page.content, "html.parser")
price = soup.find(class_ = "text-right portal-price").get_text()
print(price)
Shop thousands of Hertz Certified used cars at incredible below market prices. We offer a warranty, a buy back guarantee, home delivery, and more!
Traceback (most recent call last):
File "/Users/rahuldas/Desktop/web scraping hertz/web_scraping_hertz.py", line 10, in <module>
price = soup.find(class_ = "text-right portal-price").get_text()
AttributeError: 'NoneType' object has no attribute 'get_text'
i'm trying to scrape the price, but it doesn't seem to work
oh that's what they were asking
the terminal didn't help me at/ all
what
import discord
import random
TOKEN = "sike you thought"
client = discord.Client()
@client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
@client.event
async def on_message(message):
username = str(message.author).split("#")[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username} : {user_message} ({channel})')
if message.author == client.user():
return
if message.channel.name == 'testing-2':
if user_message.lower() == "hello":
await message.channel.send == (f'Hello {username}!')
return
if user_message.lower() == "bye":
await message.channel.send == (f'See ya later {username}!')
return
this is the command
the bot isn't responding
and the terminal says
man i can't copy the terminal
from bs4 import BeautifulSoup
import requests
url = "https://www.hertzcarsales.com/certified/Ford/2019-Ford-Fiesta-7406eaed0a0e0a905aaa0f8910f96833.htm"
page = requests.get(url)
soup = BeautifulSoup(page.content, "html.parser")
soup_2 = BeautifulSoup(soup.prettify(), "html.parser")
#print(soup_2)
title = soup_2.find(class_="text-muted font-weight-bold BLANK").get_text()
price = soup_2.find(class_="price-value").get_text()
transmission = soup_2.find(class_="mr-3").get_text()
print(title)
print(price)
print(transmission)
i don't get how the class tag says it's automatic
i use .get_text
and still it doesn't give me the "Automatic"
yeah i'm not so sure
i specify the class name just like i did w the other ones
still don't know
I am trying to work out task management with flask. So, say on a dashboard they submit a form and the form sends an rest API to another part of my server to do a task. If the page is refreshed will the task still happen?
Or if at the same time, another task is sent, does flask automatically handle it all?
you mean like a todo?
or like a lambda?
does anyone know?
I doubt anyone will follow what you're trying to ask here without seeing some code
i am so lost
Does anyone know how I can see the actual implementation of the DOM?
The actual classes for Node, EventTarget, Document, and so on, in code form?
You'd have to pick a browser and look at its source code
Yes the major browsers are all big code bases
I've tried to find the relevant parts a few times, but its all distributed
My task is to write a faithful implementation of the dom protocol (since technically its an interface designed to be implemented in any language) in python
You could try to search a browser engine's bug tracker for the classes you're interested in
Usually the issues link to diffs for fixes and whatnot
That should give you an idea of where things are located
There's this document
Which I think is basically the recipe. But the tendrils of the DOM extend minutely, in every direction, throughout the mechanics of the browser itself that it's hard to know what I need to emulate
What I think I need is a base EventTarget class and a base Node class
Hello!
I have a question. So I am trying to return a different html template with flask but when I click the button to do it, it doesn't work
I need a bunch of node subclasses which act as mixins, and those are mixed together in various combinations to create elements, documents, document fragments, concrete text node classes of various types
import os
import openai
openai.api_key = os.getenv("API KEY")
app = Flask(__name__) # Create an Instance
@app.route('/') # Route the Function
def main(): # Run the function
return render_template('index.html') # Render the template
@app.route('/generate', methods=["POST", "GET"])
def generate():
return render_template("generate.html")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True) # Run the Application (in debug mode)```
<input type="button" name="submit" value="Run Script">
</form>```
I don't have anything in the generate html for the button
Are you referring to when you do an import like import * as namespace from "module"?
No, no, I'm talking about javascript
Yes, that is JavaScript code.
1.4. Namespaces
To validate a qualifiedName, throw an "InvalidCharacterError" DOMException if qualifiedName does not match the QName production.
To validate and extract a namespace and qualifiedName, run these steps:
If namespace is the empty string, then set it to null.
Validate qualifiedName.
...```
Is your question in the context of the JS language itself or in the context of the DOM standard?
Seems to be the latter
Yeah, the DOM standard
I'm not sure then
Perhaps related to XML namespaces? I dunno
Yes, that actually seems to be the case after looking at the DOM standard
Here is where you can read about them https://www.w3.org/TR/REC-xml-names/
Danke
where could I look to get help in reading webpages for updated text? is this the channel or somewhere else?
bs4 is so irritating
As in web scraping? https://realpython.com/python-web-scraping-practical-introduction/
cheers buddy,... will check it out
AttributeError: 'NoneType' object has no attribute 'split' Why im always getting this error?
Sending your code will be much appreciated.
File "D:\Anaconda\envs\Web3\lib\socketserver.py", line 647, in process_request_thread
self.finish_request(request, client_address)
File "D:\Anaconda\envs\Web3\lib\socketserver.py", line 357, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "D:\Anaconda\envs\Web3\lib\socketserver.py", line 717, in __init__
self.handle()
File "D:\Anaconda\envs\Web3\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle
self.handle_one_request()
File "D:\Anaconda\envs\Web3\lib\site-packages\django\core\servers\basehttp.py", line 194, in handle_one_request
handler.run(self.server.get_app())
File "D:\Anaconda\envs\Web3\lib\wsgiref\handlers.py", line 144, in run
self.close()
File "D:\Anaconda\envs\Web3\lib\site-packages\django\core\servers\basehttp.py", line 111, in close
super().close()
File "D:\Anaconda\envs\Web3\lib\wsgiref\simple_server.py", line 35, in close
self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'
I think the problem is with this wsgi file.
it doesnt affect my web, but the error always shows up
That's the error, not the code.
Django question: How can I make URLs in my urls.py be case insensitive?
That solution doesn't work anymore, Django deprecated it
Hi, im using datatables.
Anyone know how to resize this?
somehow the search box over rides my columnDefs option.
That's quite good for a single-page exploration of a number of well laid-out design elements. I like the overall design language. My personal preference is for more white space. Given the focus of the landing page, maybe greater padding for elements while continuing to use a screen-width container.
Are you coding in Django or Flask?
Thanks greate feedback! Have a nice day
I definitely appreciate the depth of research thru your comp sci degree, along with techniques you must be exposed to. For example, the loading rocket that then gets used for the top of page icon...
...that's sweet design language. Definitely talent there 🙂
Creative 🙂
Thanks! I was thinking so hard to make it as perfect as I want since I gonna use this for my future workpath to showcase my projects