#web-development
2 messages · Page 174 of 1
yes
@arctic wraith ^^ ik u'll fix it , it's ezz for u pro
can we perform template inheritance from another app?
hello can someone help me with html?
??
what's your problem
I just heard about it from a podcast it seems like a mix between Django and flask
so no experience sorry
no worries. i remember looking at it years ago. seems legit
In Django you can use {% extends 'other_app/template.html' %}
Hey, my selenium keeps opening 'data;' Help please
Hello guys i need a help plz:
I use flask and I wonder if i can send a post request with js script to from a page loaded by route A to a route B ?
to be more cleare my page render in this route
and i want to send something like :
is it flask who block it, or its a mistake i did ?
Could anyone help me? guys, help plz
what do you mean? what's actually happening?
use Order.objects.create or Order.create or just use entry.save() method.
done
are u learning from docs lmao , bro dont mind but u r learning not understanding
im sure u have somewhere used
did you add your app on installed_app on your settings.py file
or set up your urls and views?
btw that was not problem
show ss of ur that html and urls.py file
Error 405 method not allowed
try getting one method on one path
does your route support posts?
maybe it doesn't accept multiple methods?
Yes it does support post
can i see that route?
when i send i request to another route it thas not allow me
it need to start with the same route
Just try to google bro
I'm learning Django from [THIS][1] tutorial. Everything worked perfectly until this step:
Now change your polls/index.html template from:
<li><a href="{% url 'detail' poll.id %}">{{ p...
cause 405 means you're using a method that's not supported on that route
get and post is essential, so I don't think that is not support
does flask block it because its a different route ? maybe security reason ?
you can limit whether it accepts post or get only. it doesn't support both by default
idk js, so I can't help you @naive blaze
I don't think this is a security issue
are you making a request to this exact route?
please before asking and waiting everything from us, just google guys
after if you couldn't solve, come to ask
I love stack ❤️
the goal is to send it to other route, if i start with "users/compact-table/ it work
if i send to "Somthing-else/
it does not work
for other route sending data, use redirect method if it exists with data
but include with two args is not supported
you want to target a route by using a different route?
maybe error is linked to them?
i googled; this is not the same issue here.
and what is your problem?
this doesn't work
did you look the link I sent you?
hmmm okey, send your codes
did you follow all tutorial
yes exactly
everything is necessery for that app.
I'm at 4th tutorial
yup
polls/urls.py
from django.urls import path
from . import views
aap_name = "polls"
urlpatterns = [
path("", views.index, name="index"),
path("<int:question_id>/", views.detail, name="detail"),
path("<int:question_id>/results/", views.results, name="results"),
path("<int:question_id>/vote/", views.vote, name="vote"),
]
not possible mate. unless you redirect like suggested
mysite/urls.py
from django.contrib import admin
from django.urls import include, path
app_name = "polls"
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
did you add your app settings.py file
there is a list on there called installed_app like...
template/polls/detail.html
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
<fieldset>
<legend><h1>{{ question.question_text }}</legend></h1>
{% if error_message %}<p><strong> {{ error_message }}</p></strong> {% endif %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{choice.id}}">
<label for="choice{{ forloop.counter}}">{{ choice.choice_text }}</label><br>
{% endfor %}
</fieldset>
<input type="submit" value="Vote ~CLICK~">
</form>
Thanks for help no to choice but to figure out a way
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
pastebin was banned on my country :/
idk, if it helps you but I cannot help you due to I am not on pc
xD
:/
idk, what's is the problem
I will try solve this tomorrow, It's late.
i sent an error
yeah but what is causing this, idk it.
you include('polls.urls'), but the way you're using the URL, Django expects you to register it to a namespace
you probably want include('polls.urls', namespace='polls')
do you still ahve the error around?
if it's late, go to sleep! we'll be here tomorrow
okay 🙂 thank you for every help,
bro. Goodnight!
aap_name ? you have the same name in both of the app_name urls , thus I don't think django can differentiate between the two apps if the have the same app_name variable , also it has typo
also try leaving the action attribute empty, thus the form still should work, since when you leave it by default the action will be set to the current page
Hi
I've my project with django postgres and redis, it's a chat application
I'm looking to scale it, anyone with experience of where they've deployed it?
I've my test on heroku, I've been trying to deploy production to AWS beanstalk and failing at it. If anyone has any guide, would be helpful, the one's on Google are outdated and doesn't seem to work and AWS docs was really bad
if you want to learn a bit, then just getting a regular VPS (like digitalocean droplet, hetzner server, netcup vps) to deploy on is probably the best way to go. as for scaling it, it depends what your current bottleneck is, i would assume the first place to look would be the django app?
is there a tutorial on building APIs with django without DRF? everything seems to suggest DRF but i want a barebones look at it
that depends on what you want your API to do - the most basic API could just receive a request, decode it from json, lookup some data, and serialize & return that as json
then you’ll probably also want things such as token authorization, validation, etc.
for validation, you could use database constraints, …
yeah i want to do all that
returning as json first of all
since that is not clear from the tutorials
there’s a section on JsonResponse here that might be helpful https://docs.djangoproject.com/en/3.2/ref/request-response/ i can’t copy a direct link since i’m on phone, sorry
btw quick question, what are the default names for html, cs, and js files? On the mdn docs I saw index.html, main.css and javascript.js
Heyy can anyone please help me re-create a cool looking eportfolio?
There's no main file for js and css
Only index.html for HTML
And in nodejs, index.js is the most common entry point but that doesn't matter in the browser
Well I want to use seperate files for css and js
But it's not a bad idea to go with index.js
That's fine
Why does the name matter to that?
so index.js and what do I call my css file?
idk I just would like to follow the general naming conventions
That's up to you, there's no real convention
I've also seen script.js an style.css are those common names?
oh i c
Some call in main.css, some styles.css, others globals.css, all are fine
script.js is pretty common, yeah
oh so what I have rn is index.html, main.css and javascript.js is all good?
wdym by this then?
As in, it doesn't matter what you name it
oh okay yeah I was a bit confused when the example from mdn had that
ohh okay sounds good then
Basically, you can name anything besides index.html whatever you want
Is there a reason for that? I've seen main.html one time
index.html is the commonly accepted entrypoint. Most services will always view that as the base of your project. (e.g. the url would be example.com instead of example.com/otherstuff)
there's github pages to host your static website. You can always look at videos for inspo ig
oh yeah that makes sense
thank you
Oh yeah and another thing
I don't know if there's reasoning behind naming it index.html, but that's what it is 🤷♂️
Is this formatting good?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<!--Link to css file-->
<link href="style.css" rel="stylesheet"/>
<!--Link to javascript file-->
<script src="script.js"></script>
Or are spaces bad
and comments no good for html
That looks fine, but you probably don't need a space between the comment and the actual line
They're usually fine, but kind of useless in this case
The fact that you're importing a css file and a js file can be easily understood by glancing at the code
You don't need to specifically say that
Right makes sense I've just started html/css not too long ago so I usually like to comment so I don't forget
are the links suppose to be under the title or nah?
That's just up to you, doesn't really matter
There are all sorts of guides on the order, but no official guidelines or anything that really matter
so there's no documentation for formatting?
Idk, html looks hard to read when all the code is clumped together
There's no official style guides afaik if that's what you mean
It can be because of its confusing-ish syntax, yeah
I prefer pug because of that actually
pug?
Is that a markup language or smt
It's an html preprocessor
Basically an alternative syntax for html
oh that's cool. good to know
let's have scripts.js 😉 that would be more general
oh, you alredy renamed, nvm
if anyone here knows how to use pythonanywhere, I'm going to need some help
I'm seeing YouTube videos showing using GitHub and cloning their website, but is there a way to have a private repo for that?
I was going to upload a ZIP file
Anyone familiar with Facebook Messenger Platform API?
script or scripts?
nah lets leave it as script
Oh kk thanks for the tip 👍
{
"object":"page",
"entry":[
{
"id":"<PAGE_ID>",
"time":1458692752478,
"messaging":[
{
"sender":{
"id":"<PSID>"
},
"recipient":{
"id":"<PAGE_ID>"
},
...
}
]
}
]
}
Event Format
`
All webhook events have a common structure that includes information you will need to process and respond to the event, including the PSID of the sender and recipient of the event. In addition to the properties shown below, each event also has its own event-specific properties.
Note that entry is an array and may contain multiple objects, so ensure your code iterates over it to process all events. For a complete description of event properties, see Webhooks Reference.
`
It says here "Note that entry is an array and may contain multiple objects, so ensure your code iterates over it to process all events."
Anyone familiar with the Facebook Messenger Platform API? I wonder in what instance are there multiple events being delivered to a webhook?
Correct app spelling
import socketio
from src.server_state import ServerState
from src.logs_handler import log, INFO, ERROR
sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins="*")
app = socketio.ASGIApp(sio)
server_state = ServerState()
# Default Events
@sio.event
async def connect(sid, environ):
server_state.workers_online += 1
server_state.add_worker(sid)
server_state.rebalance_jobs()
log(INFO, f"{sid} Connected!")
log(INFO, f"Total online workers: {server_state.workers_online}")
log(INFO, [(x.worker_sid, x.jobs) for x in server_state.worker_job_maps])
await sio.emit("sid", sid, to=sid)
@sio.event
async def disconnect(sid):
server_state.workers_online -= 1
server_state.remove_worker(sid)
log(INFO, f"{sid} Disconnected!")
log(INFO, f"Total online workers: {server_state.workers_online}")
log(INFO, [(x.worker_sid, x.jobs) for x in server_state.worker_job_maps])
@sio.event
async def get_job(sid):
pass
@sio.event
async def get_account(sid, primary_job_id):
pass
``` As you can see I'm using an `ASYNC socket.io` server. I wanted to ask whether I am required to spin a thread to resolve the request on ASYNC socket.io because some requests might take some time (1s - 3s) to resolve and I don't wanna interrupt other requests that might happen while solving this request
Example: On connection my server needs to rebalance jobs for all the connected workers and it might take some time
I'm running the server using uvicorn like so: uvicorn server:app
youll have to use ssh for cloning private repo
should i use fastapi or django as backend? planning to use it with both react and react native and mysql as db
i asked this over at #software-architecture yesterday and was told to use fastapi instead, not sure if thats better or worse:
so im creating a project with django as backend and react as frontend, should i:
a) use django-admin startproject then create an app called frontend and manually add all the required stuff for react (since idk still how to npx create-react-app in a django app, it just doesnt work for me fsr)
b) use django-admin startproject then without creating an app, do npx create-react-app then somehow link django to it? im not sure how that would work
c) use npx create-react-app then somehow create a django project inside, not sure how that would work either
any help would be appreciated!
class Order(models.Model):
name=models.CharField(max_length=50)
email=models.EmailField()
author=models.OneToOneField(User,on_delete=models.CASCADE,unique=False)
phone_no=models.IntegerField(default=0)
address=models.CharField(max_length=100)
zipcode=models.IntegerField(default=0)
def __str__(self):
return self.name``` so when i'm out the form from user for example admin
isn't django admin like a pre built interface? how would you even use it in something like react?
wdym?
ive followed some tutorials that uses django and react combinations and it works pretty well
you know how django uses template rendering etc, that stuff is irrelevant when you use something like react. i don't know if i'm making sense here
ah i see what u mean
yea its kinda counter intuitive in a sense
but i thought some big companies like instagram uses django and react
i mean you can use it but you'll be using django like an api mostly
i see
same for any other backend framework really
class Order(models.Model):
name=models.CharField(max_length=50)
email=models.EmailField()
author=models.OneToOneField(User,on_delete=models.CASCADE,unique=False)
phone_no=models.IntegerField(default=0)
address=models.CharField(max_length=100)
zipcode=models.IntegerField(default=0)
def __str__(self):
return self.name``` ```py
@login_required
def order(request):
if request.method=='POST':
name=request.POST.get('name')
email=request.POST.get('email')
author=request.user
phone_no=request.POST.get('phone_no')
address=request.POST.get('address')
zipcode=request.POST.get('zipcode')
print(author)
entry1=Order(name=name,email=email,author=author,phone_no=phone_no,address=address,zipcode=zipcode)
entry1.save()
return HttpResponseRedirect('/')
return render(request,'index/order.html')``` so the problem here is the 1st time when i filled the form when logged in from account called "admin" it works then i again tried to fill same form when logged in with user called "admin" it throws error , then i filled form with user "test" it works hence it shows user can fill form only 1 time how can i fix that error ```IntegrityError at /order/
UNIQUE constraint failed: index_order.author_id
it depends on what for you are going to use it
django rest framework as backend services fine to react
trying to build something like a twitter/instagram clone
instagram was built with django 😉
the only issue with django you will have
partially limited async support
it works for views, and there are django channels for web sockets, that's ok mostly
yea thats the thing i found on google
but Django ORM is sync at the moment
that's why Fast API can be preffered
since it has no in built ORM in it
you can setup from the start async friendly ORM
not sure how to answer that
there are so many ways to speed up web app
tahts true
that at the end it will probably no matter which framework you used at the start
the good things about django, that it brings really fast development at least
any feature is just plug and play
so it could make better end result just because you will have more time to use for development of architecture and optimization
i hope they will eliminate their last weakness with ORM not async supported though
we can expect it around december to see perhaps
oooo
it is scheduled for Django 4.0
yeah
so im extremely new to web designing as in ive pretty much never done it but im trying to find if theres a way to read mouse coordinates through something like flask or django. I normally use tkinter which has the ability to track mouse coordinates, but I was considering trying a website but im struggling to find ways to track mouse movement. does anyone know a way to do this? if someone responds please @ me 🙂
use javascript, it handles frontend interaction
would i be able to do that with something like flask or django or would i do something else?
it doesnt matter what backend you use
you're just using javascript to read the mouse co-ordinates, and sending them to the backend if that's what you want too do
alright sounds good ill definitely look into that thanks
Is there a way to see something like this in VSCode?
project isn't uploaded to GitHub but I am curious
wakatime plugin
it gives you the time you spend on a certain project, also shows the IDE, languages, OS that you have used
look it up
are you able to have it show the stats for all the code in your project?
as in... not recording... but just how the project is as it stands
wait a minute...
is this it?
no, nevermind
if you mean as in what portion of languages you have used in the project, i think when you log in the site
at the bottom there are projects section
and when you click on some project it shous you some statistics
but im not sure if its the time spend on that certain project and language or what languages portion are in the project
help
Looks like it is time spent
But that is also something I’ve wondered about so I am keeping this plug-in
You can use HTML, CSS , JS for mouse coordinations
hey can i ask a question
my concern is that my css peak even if its enabled, it won't let me peak from html to css
and vice versa
hello is anybody around?
Because you have one to one field
So user can only have one order with this unique constraint
uhhh hello anybody?
tried to restart the vscode
tried uninstall and reinstall and nothing happens
i have a relatively simple (i think) issue that i'm not sure how to solve with django regarding models and subclassing a model
i have a Payment class (inheriting from models.Model) and i want to extend this into more subclasses, because each Payment has a payment_method type which is a string like 'creditcard', 'paypal', etc..
so i have created a CreditCard class which inherits from Payment and has fields like name, number, cvv and so on. and another PayPal class which has fields like email and so on.
what i want to achieve is something where, when someone is creating a new payment, when they specify the payment_method string, they also have to add the corresponding extra fields specific to that payment method -- e.g. they would have to include the number of the credit card if they choose 'credticard'
how do i go about this?
guys Is there any way i can clean a specific common field between let say 3-4 forms and to write a Mixin for it? and if so how can i do it
instead of copy pasting the same stuff in all forms
dont inherit the models in models, just inherit django's Model class on every model in your code and to link them between use ForeignField
to look details search: Django ForeignField
thank you! i'll look for that
Follow the tutorial of django there is an example in there.
This is the table setup I have for this stuff #databases message
But is your question about how to collect the different info for different payment methods?
that looks similar to what i want, except i guess i dont need id for particular payment method types
i want something like when i hit /api/payments itll show me every payment and generic information (common to all) and then when i hit /api/payments/<id> itll show me all that payment's data including its specific parameters like number if it's a credit card
Well in my example ID is needed as it the transaction tables makes reference to it from payable id.
this, too, yes
because i want one /api/payments endpoint with a POST on it where i'm expecting the given parameters depending on the payment_method the body has
This is a matter of how you write the query.
When I read that completely, I realized the way I told you is not relative with this. So you can make html page form in order to the user select the method type and type other necessary informations about payment and get them with POST method and create your Payment Model
For your payment data collection just have some logic that show le the appropriate view for each payment method. For example, for card payment you will show the credit card form, and for PayPal you will redirect to PayPal
I think you shouldn't create submodels which inherits base Payments model and just define payment_method string with data getting from a form page.
Also for this certain design patterns can make this easy, and more maintainable so in the future it’s easier to add or remove payment methods without affecting other paths of the code.
{
"object": "page",
"entry": [
{
"id": "<PAGE_ID>",
"time": 1458692752478,
"messaging": [
{
"sender": {
"id": "<PSID>"
},
"recipient": {
"id": "<PAGE_ID>"
},
"timestamp": 1458692752478,
"message": {
"mid": "mid.1457764197618:41d102a3e1ae206a38",
"text": "hello, world!",
"quick_reply": {
"payload": "<DEVELOPER_DEFINED_PAYLOAD>"
}
}
}
]
}
]
}
Here's a typical payload when a user sends a message (Facebook Messenger Paltform API).
My webhook receives this POST request however, let's say we've asked the user to provide some text input.
How would we generally setup something that:
- Catches that it's the same user in order to respond to the same user
- Wait for their text input
How can I redirect to a external url with flask?
how can i add a field to all my forms and not do it by hand ? any ideas appreciated
So how can i have multiple (infinite ) products for a single (particular ) user
I don’t understand, I thought you showed code for user and orders. Not products
without django forms?
TypeError at /order/
Direct assignment to the forward side of a many-to-many set is prohibited. Use author.set() instead.```
Could somebody help me? "py manage.py runserver" returns line with text "python" and refuses to start server. What do I do?
python manage.py runserver
some response
what's the error?
send a screenshot
no error, I have no idea what to do
are you in the root directory of your project when you run the command?
did you start the project with django-admin?
I started project with django-admin, created venv. Programming on windows
@opaque rivet bro help
Hi i am getting this error, anyone could help? ``/usr/local/bin/python3.9 /Users/vincentz/Documents/sre-rre/app/src/controller/init.py
Traceback (most recent call last):
File "/Users/vincentz/Documents/sre-rre/app/src/controller/init.py", line 2, in <module>
import pandas
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/init.py", line 11, in <module>
import(dependency)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/numpy/init.py", line 139, in <module>
vinfo = get_versions()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/numpy/_version.py", line 21, in get_versions
return json.loads(version_json)
AttributeError: module 'json' has no attribute 'loads'
Process finished with exit code 1``
yes, my current folder name is
no any other suggestions might try?
I couldn't understand why numpy couldn't find json's loads method idk I think maybe it was installed wrong somehow :/
haah, i searched on stackoverflow people has the same issue, all changed file name then its fine, but in my case, my file name is fine, so i don;t know what else to do
#help-potato help in data scrapping
open your command prompt and type python to switch python shell
then type these line-by-line
> import json
> json.loads({'test': 'testing this method whether exists or not'})
check your python path
import sys
print(sys.path)
because there is something wrong in your modules path
like /Library/Frameworks/Python.framework, it should have been like python/Lib/site-packages/... but not...
if you change your packages path you should set this folder's path to your PATH or PYTHONPATH environments.
@grave pine
Help please
I've heard that socket in used in creating a chat app, so if you are a python backend programmer and you're told to make one(an API that does that) to send to the front-end, how do one go about it?
quick help
extra_kwargs = {"email": {"required": False}}
how do I write if I have an additional field "speciality" that I also want to set to false?
Well you would definitely need a socket but so would every other program that communicated online. Check out the channels.readthedocs.io/en/stable/tutorial page. A pretty basic chat app gets built
Channels takes away the need to figure out a bunch of socket stuff as well as Django’s auth and session system
It’s pretty cool
But if you really want to learn how to use the WebSocket API then I believe Mozilla has a few articles that might interest you
Thanks,
the admin page of my site is missing CSS . I've deployed it on pythonanywhere using django framework . Anyone who can help with the same
@wet mortar check the network analysis tab of your browser, do you get 404 for the static pages? does pythonanywhere host the static files?
how do i do that ?
and 404 error is there
There are 3 main things to do:
set STATIC_ROOT in settings.py
run python2.7 manage.py collectstatic (or python3.5 or python3.6 as appropriate)
set up a Static Files entry on the PythonAnywhere Web ta
I think this document is what you're looking for
You need to run python manage.py collectstatic. Static files are then generated.
@meager anchor
i have them hosted
I am aware.
You can open a console. Activate the virtualenv (if using one) and run that command.
specified as well
ohk so
lemme change
plz help me
also ^
sorry if i sound a lil mad , but its been 2+ hours
class Order(models.Model):
name=models.CharField(max_length=50)
email=models.EmailField()
author=models.ManyToManyField(User)
phone_no=models.IntegerField(default=0)
address=models.CharField(max_length=100)
zipcode=models.IntegerField(default=0)
def __str__(self):
return self.name```
not working :(
TypeError at /order/
Direct assignment to the forward side of a many-to-many set is prohibited. Use author.set() instead.
``` this error tooo
@wet mortar including the directory?
You're either doing relationships incorrectly or trying to assign through a reverse lookup which to my knowledge isnt possible.
yes
views.py ?
what u mean
bruh its correct trust me
Whats your static_url and static_root set to in settings.py
Literally exactly that. Best bet if you're uncertain is to refer the documentation for Django. EX: Many to one, M2M etc
Try this
STATIC_ROOT = os.path.join(BASE_DIR,
"static")
i need to import os for that
Yes
first import os then Path(BASE_DIR , "static")
un
im sure it will work
seee
and yes import os
Just try it lol
and paste
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
;-;
configuration should stay in your settings file/package. You don't want it scattered.
Single source of truth
f finally . thankyouuuuuu
Do you know what was wrong?
it was not directed ?
also
my bad
i was doing /home/parvashah/.virtualenvs/myproj/lib/python3.8/dist-packages/django/contrib/admin/static/admin instead of /home/parvashah/.virtualenvs/myproj/lib/python3.8/site-packages/django/contrib/admin/static/admin
It happens man. One time I lost almost 4 hours over a comma.
you could've said this earlier
i feel ya man
where you from ?
india :/
...
Show us your views lol
my views:
oh
what do you do ?
@login_required
def order(request):
if request.method=='POST':
name=request.POST.get('name')
email=request.POST.get('email')
author=request.user
phone_no=request.POST.get('phone_no')
address=request.POST.get('address')
zipcode=request.POST.get('zipcode')
print(author)
entry1=Order(name=name,email=email,author=author,phone_no=phone_no,address=address,zipcode=zipcode)
entry1.save()
return HttpResponseRedirect('/')
return render(request,'index/order.html')```
What are you doing on the template?
it's for ecommerce site and i used author here so every user can see thier order history before a day i was doing from OneToOneField so it was working but was not taking more then 1product from same user
so i got to know about this field
Manytomany
try creating a dict here and passing it in your render function ?
so Manyonmany should work ig
Many to many would be if an order can belong to multiple users
author=models.ManyToManyField(User)
I guess models.ForeignKey will be more suitable for this
there is nothing wrong with using a many to many here. It depends on how he wants to represent the relationships.
for example he would use a onetomany
ohh
and then use object_set but that depends on the use case
You will be using ManyToManyField when creating a custom user profile etc...
A user has many orders, so you want the foreign key on the orders table. This way a user can have many orders and each order belongs to a single user.
Oh wait sorry, you will be using OneToOneField for a custom user profile
To build upon that if you want all orders for a user (to render in a template or view) you would then use ```
orders = User.order_set.all()
i have idea of OnetoOne
ManyToManyField will be using in creating a like button etc...
Using a foreign key as stated above is a OneToMany
I’ve already said when. Are you ignoring messages?
nope
Then not sure why you ask again
ohh
cez
it's 1:37 am
and my mind says
u r noob
alrdy done
@dusk portal You should consider looking at e-commerce systems and how they work and are structured. They can get complex and so if you are stuck on something simple like this then you will face more issues later
Well yeah if you don’t plan or think it through properly you’ll end up in a mess
Can someone explain to me how domains work? How do people claim them and how do all of those websites that sell domains get them?
The people who have the domain leave some kind of contact info for someone who wants it to reach out to them, then the website like negotiates on your behalf to get the domain for you for a fee, atleast I think that's how it works
And where did the people who have the domain get it from?
Check this out
I don't though.
wait guys im new to flask so im not sure on what things i need to learn in order to make like a loging and signup page on flask
Look at freecodecamps latest flask tutorial video on YT. the guy goes over user registration and login near the end (it’s split into sections)
ah yes im looking at that but another question i have is do i need to do the models.py
Unknown from me, I haven’t got that far yet.
ah ok i was just asking if i need the models.py for the login and registration
I assume so, since you need to save your users to the db and read from it
yah i see
Hi this is more related to javascript and html than python so am sorry, but i need a help..
Im trying to store json in html data attribute then take it out edit that and save again, but i have problem with encoding all the time my "x":false will always be saved as "x":"false".
Can someone tell me how to encode it ?
Is it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse you need?
well i know about parse and am parsing it, but prbbly in the wrong way cuz it always get "false" on resaving it
You want to use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify to make it a string to store, and then you need to parse to get it back out again.
Well do i need to stringify object when i want to save him in html data element using element.attr("data-x",val) ?
i tried to do the step where it creates a db but it didn't create one
the db you need to create manually, models will be used to create the schema in the db
ahhh
when you run makemigrations or how it is called in flask
so i just make a new file for users say called users.db ?
it is not straight, check the flask docs about this
what?
check the flask docs about this
okk
I have a question in #🤡help-banana if someone would like to help me
Morning ppl, I wanna ask something about validators. I have an ImageField, and I'm wondering is it enough the built in validator in the actual ImageField, or should I use the django- validate_image_file_extension
also what do you consider a good max image file size (like 1 MB 2mb ?)
uhm, thats way to low, 8 is good
i guess the more resolution more pixels and higher file size ?
Im building a photo uploading site, and Im wondering is there any good reason to have different image file size validations for the normal image and a profile image (since profile image are just small pictures)
Hello guys, can someone tell me what I'm missing!
I start using django_restframework, I wrote a simple serializer to get started, when I start the shell and try to import the file I get this error
>>> from myapp.serializers import NotesSerializer
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/omer358/PycharmProjects/NotesApp/Notes/myapp/serializers.py", line 2, in <module>
from Notes.myapp.models import Notes
ModuleNotFoundError: No module named 'Notes.myapp'
>>>
when I tried to import my model it worked just fine!
this the structure of my project:
(NotesApp) omer358@OMO:~/PycharmProjects/NotesApp$ tree
.
├── main.py
├── Notes
│ ├── db.sqlite3
│ ├── manage.py
│ ├── myapp
│ │ ├── admin.py
│ │ ├── apps.py
│ │ ├── __init__.py
│ │ ├── migrations
│ │ │ ├── 0001_initial.py
│ │ │ ├── 0002_rename_last_modified_notes_last_modify.py
│ │ │ ├── 0003_rename_last_modify_notes_last_modified.py
│ │ │ ├── 0004_rename_last_modified_notes_modified_at.py
│ │ │ ├── __init__.py
│ │ │ └── __pycache__
│ │ │ ├── 0001_initial.cpython-39.pyc
│ │ │ ├── 0002_rename_last_modified_notes_last_modify.cpython-39.pyc
│ │ │ ├── 0003_rename_last_modify_notes_last_modified.cpython-39.pyc
│ │ │ ├── 0004_rename_last_modified_notes_modified_at.cpython-39.pyc
│ │ │ └── __init__.cpython-39.pyc
│ │ ├── models.py
│ │ ├── __pycache__
│ │ │ ├── admin.cpython-39.pyc
│ │ │ ├── apps.cpython-39.pyc
│ │ │ ├── __init__.cpython-39.pyc
│ │ │ ├── models.cpython-39.pyc
│ │ │ ├── serializers.cpython-39.pyc
│ │ │ ├── urls.cpython-39.pyc
│ │ │ └── views.cpython-39.pyc
│ │ ├── serializers.py
│ │ ├── templates
│ │ │ └── myapp
│ │ │ ├── detail.html
│ │ │ └── index.html
│ │ ├── tests
│ │ │ ├── __init__.py
│ │ │ ├── __pycache__
│ │ │ │ ├── __init__.cpython-39.pyc
│ │ │ │ └── test_models.cpython-39.pyc
│ │ │ └── test_models.py
│ │ ├── urls.py
│ │ └── views.py
│ └── Notes
│ ├── asgi.py
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-39.pyc
│ │ ├── settings.cpython-39.pyc
│ │ ├── urls.cpython-39.pyc
│ │ └── wsgi.cpython-39.pyc
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── README.md
how can i hit breakpoint in post_delete signal, no matter what i do, the ide just doesn't go to the signal
you most likely want to import from myapp.models directly
Notes in this case is the (django) project with asgi.py etc.
how did you set the breakpoint? what if the signal isn't being called?
yes, that sounds like a sane thing to do. one thing lots of websites do is limit the resolution of your images
it does get called because it is a signal that after deleting profile image to delete it from the media folder and not store it since it is deleted
@glacial perch hello! I'm afraid we don't allow advertisement of non-python projects here.
then that leads to the other question, how did you set the breakpoint? in your IDE? in the code?
in the IDE
im using vscode and just put the red dot on the signal
i tried to put it on the view where the .delete() is called but it just continues ahead and doesn't jump to the file where my signal is
@login_required
def profile_details(request):
profile = Profile.objects.get(user_id=request.user.id)
profile.full_name = profile.first_name + ' '+ profile.last_name
user_images = request.user.photo_set.count()
user_comments = request.user.comment_set.count()
user_liked = request.user.commentlike_set.count()
recent_photos = request.user.photo_set.all().order_by('-posted_at')[:4]
if request.method == 'POST':
form = ProfileForm(request.POST, request.FILES, instance=profile)
delete_image_form = DeleteProfileImageForm(request.POST)
if form.is_valid() and delete_image_form.is_valid():
profile = form.save(commit=False)
if delete_image_form.cleaned_data['delete_image'] == 'True':
profile.image.delete()
else:
profile.save()
return redirect('profile')
else:
form = ProfileForm(instance=profile)
delete_image_form = DeleteProfileImageForm()
context = {
'form': form,
'delete_image_form': delete_image_form,
'profile': profile,
'user_images': user_images,
'user_comments': user_comments,
'user_liked': user_liked,
'recent_photos': recent_photos,
}
return render(request, 'profile/profile.html', context)
this is my view and i tried to put it on the line where is profile.image.delete()
@receiver(post_delete, sender=Profile)
def delete_profile_image_media(sender, instance, **kwargs):
"""Removes media files when profile image is deleted."""
if instance.image:
default_storage.delete(instance.image)```
and this is my signal
try manually connecting instead of using @receiver
I had a quick DRF question of my own.
class Resource(models.Model):
uri = models.URLField(primary_key=True)
class ResourceSerializer(serializers.ModelSerializer):
class Meta:
model = models.Resource
fields = ('uri',)
class ResourceViewSet(viewsets.ReadOnlyModelViewSet):
queryset = models.Resource.objects.all()
serializer_class = serializers.ResourceSerializer
router = DefaultRouter()
router.register('resource', views.ResourceViewSet)
....
See above for a sample view, model, serializer and router config.
Imagine you have a resource like Resource(uri="https:/example.com/foo.bar")
How would I view its details.?
/api/resource/[what goes here]
Normally a primary key goes there. But since my PK itself is a URL how does it work?
I have for example tried something like /api/resource/https%3A%2F%2Fwww.example.org%2Ffiles%2F9999%2F9999.zip with no success
These are the RE printed by the DEBUG config
api/ ^resource\.(?P<format>[a-z0-9]+)/?$ [name='resource-list']
api/ ^resource/(?P<pk>[^/.]+)/$ [name='resource-detail']
I have tried encoding . with %2E with no success as well.
your resource still has an id
because the model creates a table with id and url columns
you can also specify url instead of pk in your urls or use lookup_field to change that behaviour
but I would not do it
There is no id column in my APP_NAME_Resource table
I just checked.
That is due to primary_key=True i assume.
just call any record from the db and check its id
I do not know what you are using for this, but there is an id field
id column is created by default
oh, primary key - yes
that is correct
I have not noticed it
why do you do it?
it makes sense to me URI is unique.
just use the default, do not overcomplicate things
just make it unique
unique=True
sure i can not make uri primary. But what is the solution for this? Are string primary keys just not possible in DRF
i don't know what i'm doing wrong, since other string primary keys work fine.
maybe possible but what is the point for that?
just URI's don't work.
uri's have some special characters, which may break something
I would not do it any way
well there's no explicit point. String PKs are usually equally fast as integer PKs and in this case i wouldn't have to make a separate column and users could identify the resource with the URI
why have id and a URI?
also it will significantly decrease the performance
of course
imagine how your urls will look https://my-domain.com/https://sfghskjhg/sdlfsldkfj?slkdjf=lskdjflsj
😆
but that makes sense no?
I have viewing a detail for that particular URI.
So to me it is much better than https://my-domain.com/some_opaque_id
There is virtually no performance difference between integer and string primary keys for my use case.
hi, is it right place ask for help regarding selenium I am having difficulty while running it
there are also help channels, which you can use
oh, Thanks I thought it's only relate to python so was hesitant
if you use selenium with python - also fine
but I am not local, so no binding here 😆
let me try asking
What's the most practical way in django to check if data matches data in database. I've been using
try:
if Model.objects.get(date__iso_week_day=selected_weekday):
# Logic
except: ObjectDoesNotExist:
# Logic```
is that the most effective & practical way?
No Sry It is Not For any Promotion I just created an Web Dev project so I asked for reviews
but without if . for if you can use filter().exists()
actually, with if also works
yeah, I've been using the if in my projects. Don't know if it's bad
filter looks cleaner to me
it is fine
get gets you the item, filter just filters the queryset I think
suitable for my case
yes, but you do not need those constructions with try-except
true
also for get you need to check for multiple values: try: except: except: becomes bigger
depends on your search criteria
true
but, yes, searching on a unique filed should work
It's true that the try gets bigger and that's where need to start thinking other options
I know, some people overwrite the default get, with including the try except
but filter looks simpler solution
and get anyway uses filter 😉
it does?
but it uses filter to get the value, if I am not mistaken
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
so filter is as fast as get?
because if application needs to check 1000s of records, it needs to be fast
I was never interested in knowing it
Would be cool to discuss it with someone who has had app with large amount of records / production
probably, the difference is not that big
yeah
also try-except adds up to the time
The most important thing is that the time stays relatively close to same
looks the same to me
yeah, if it doesn't take seconds to get the data to the page, it's fine
in my experience those large apis had much bigger problems with performance than comparing get and filter 😆
I might do a test app which I load with lots of database records and test different methods
True, and filter limits the data to the matching amount so it's like get but can get multiple records in the same queryset
yes
also for me, thank you
A bit of newbie here to web development , but would flask be a good starting point to start learning web dev?
personally, I find django better for this
what benefits do you think django has over flask ?
Django is much larger than flask and has a amazing orm, it provides really useful things like User model, Admin site, Authentication system, Security etc. Django is better suited for large scaled application while Flask is great for smaller projects, now you may ask why not use django for smaller projects? Well you surely can but that would be way too complicated, with flask you can create a simple API with like 5 lines, with django you would need settings.py, urls.py, asgi.py, wsgi.py, your actual app and stuff which is too overkill for a smaller project
Imo it really depends on what you wanna do, neither Django or Flask are too hard atleast to start with. Personally I would say django because i'm a bit biased towards it 😅
Thanks for that , great information . But for someone who is a complete beginner (I have no projects set at the moment) , would you still recommend me learning django
in future I would want do larger projects , so I guess im answering my own question . Go for django
yeah, in case it gets confusing then you can try flask
Corey Schafer on YouTube has a really great Django series (he also has a great Flask series), highly recommend it. Other than that, Django documentation is also very well written
Didnt know Corey the goat had a series on Django , that sounds super
haha yeah
just want to play devils advocate here but doesnt netflix and reddit use flask ? maybe im not understanding your point , but you can still use flask for larger projects its just harder ?
nothing stops you from using flask on a larger project, or django on a smaller, but I agree with @supple bramble that django eases working on big applications very very much. i think at the scale of netflix / reddit you can just throw your 500 developer team on it and it doesn't really matter much which framework they're using
yeah thats fair , thanks
SlugRelatedField but for multiple slug_fields instead of one in Django DRF?
Okay so there is none. I just created a new serializer i guess
flask has most of the features of django, however django provides a buttton of extras, user authentication, a real db system, and all of it is meant to ensure that you can't be dumb and accidentally allow xss
as volcyy said, it eases large projects by a lot
What are you trying to do?
I am Django Beginner
So i Downloaded Django
and in that Tutorial
The Person runs
django-admin in terminal
but it isnt working in me
you should install django with python command in terminal
Ohk will try this
Uhh What do u mean ExACTLY ?
enter django-admin --version (now)
i mean enter this " python -m pip install Django"
Thanks For ur Time but Didnt Work
I don't use Django but check the tutorial you're using for the steps that were done before typing django-admin. Like starting a project folder with certain python files and all that stuff
Yea just got an Intel that first create a Virtual Environment
Will Check'
it
Install django in a python virtual environment
Use src="{{url_for('static', filename='1.jpg')}}"
personally, I think, the django's complexity is its strong point, also for a beginner. Flask is built in such a way, that it only has a small number of functionalities and you need to search and integrate into your project the ones, which are missing, i.e. almost everyhting. Then you may have some trouble to make them all working together. Django has the most of the things included and setup. So you just start a project with 2 commands and it has all the things you need already structured for you in a convenient way (there was a comment about creating all those, but they are created for you automagically). i see more advantages than disadvantages - all the components are there, you learn to properly structure your project, you learn about the flow request-response, easy db integration, great orm, authn/authz, pagination, serialisation via DRF etc. etc.
Yeah
The main problem with Django is it's complexity for beginners
If you are not that familiar with python even the official Django tutorial can get a little confusing
true
My question might be silly, I have a doubt
What's use of learning HTML when website hosting and making sites are there and we can design the website through wordpress. I know HTML but still don't know how I implement it to make one website. Someone please answer..
Making web sites using HTML, CSS and JavaScript give more control over what you are building
When I send a post request to my Django API
I get a Bad Request error xhr.js:177 POST http://localhost:8000/api/create-post/ 400 (Bad Request)
this is the view in my django api ```py
class CreatePost(generics.CreateAPIView):
permission_classes = [permissions.IsAuthenticated]
serializer_class = PostSerializer
queryset = Post.objects.all()```
this is the urls ```py
urlpatterns = [
path('search/', PostListDetailfilter.as_view(), name='postsearch'),
path('', PostList.as_view(), name='listcreate'),
path('posts/str:slug/', PostDetail.as_view(), name='detailcreate'),
path('create-post/', CreatePost.as_view(), name='createpost')
]
and this is the function in my react component ```jsx
afterSubmit = () => {
console.log(this.state.data);
axiosInstance
.post(apiURL + "create-post/", {
title: this.state.data.title,
author: this.props.users.filter(
(user) => user.username == localStorage.getItem("currentUser")
)[0].id,
excerpt: this.state.data.excerpt,
content: this.state.data.content,
})
.then((res) => {
this.props.history.replace("/");
console.log("foo");
});
};``` This is the method that runs when I click the submit button.
I have a flask app which runs fine from pycharm but when I try to run it with the same venv from the command line, it can't find the stuff it's supposed to import
does anyone have any idea why that might be?
What the difference between nav and header in use case
nav is anything that could be used for navigation. Things like footers also often include navs
Header is specifically the top part of the page
But I know the footer used to be in the end of page
How it can be in nav
Nav doesn't mean top of the page
It just means navigation
quite the opposite navs can be in the footer
for example on this website, the footer is a bunch of links to navigate to various pages
That's mean the nav tag for links to navigate in the wep page
Yes
The nav tag can hold anything that's used for navigation
well, what's the error in your django console?
if there is none, print it in your .catch() block. any responses with non 2xx codes will invoke the .catch() block as they'll raise an error.
axios.post("").then(...).catch(response => console.log(response.response))
I'll try that
That helped me out man!
I got to know from response.response.data that I wasn't specifying a slug field
Hello, I am new to flask website development and i am running into an error.
When i try to execute the command db.create_all() its not creating the users.db file that it is supposed to
is there any fix to this?
:incoming_envelope: :ok_hand: applied mute to @tired siren until <t:1627171184:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 118 newlines in 10s).
!unmute 535867884711444491
:incoming_envelope: :ok_hand: pardoned infraction mute for @tired siren.
!paste @tired siren Use this.
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
alright
here it is
It is an AWS, django, nginx and gunicorn related question
A while I made a post on discord forum to implement a new feature. Could do with a few more upvotes and it might get recognised.
https://support.discord.com/hc/en-us/community/posts/4403067294487-Screen-Share-Preview-Resizeable-
preview: https://streamable.com/5pv2bo
maybe you could elaborate
What are you looking for?
in flask when i do {{ form.username.label() }} i get this error
did they change this?
or am i missing something
nvm i fixed it i was missing a pair of parenthesis after i defined forms=Registerform
website builders can only go so much. when it comes to actually staggering websites, they are never built using website builders like wordpress, wix etc
<form method="POST">
<input type="text" name="test" id="button1">
<button type="submit" class=test1>test</button>
<button type="submit" name="random" value="random">test</button>
</form>
.button1 {
position: relative;
bottom: 30;
}
isn't positioning the button
😦
classnames are meant to be in quotation marks
umm
nice, make it a habit to write .catch blocks to catch errors (even if it's just logging them in the console). Same goes for python, raise exceptions with your serializer errors as the message to know where you're going wrong.
still doesn't work bro
Need to make it #button1 instead of .button1 in your css
your css is now applied to the element with class button1, your CSS needs to be changed.
bottom: 30;
30 units of what? px? em? rem?
you need to specify that in the css
i did
ayo i need some advice
:c
what
i want to learn backend web developing
it it ok if i dont have much frontend knowledge?
so where do i start?
meaning your css file isn't being found, so your styles aren't being applied, possibly wrong path
i'll try pass in the path
it's fine if you don't have much frontend knowledge, you will inevitably end up learning HTML which isn't a challenge. I would start with a course, codecademy do a good one on flask/django.
is the .css file found now?
yeah, Django is the most popular and flask is your other option which is a bit more beginner friendly
hmm, in that case CTRL + F5 on your page to reset cache @native tide
and see if anything changes
still nothing
i've been trying for an hour now
not sure what the problem is
"not allowed to load local resource"
lol
oh, just realized you're trying to reposition:
<input type="text" name="test" id="button1">
To access IDs you have to use #, thank @versed python for that
#button1 {
position: relative;
bottom: 30;
}
btw, this looks like the request to submit your form, not the request to retrieve the .css file.
oh...
this is without the path
when i pass in path it says unable to retrieve local resource
I am experiencing an issue where I can run a flask app in pycharm
but it doesn't work from the command line
I think because pycharm adds the project source to PYTHONPATH
has anyone experienced this issue?
Can you show the part where you're importing the css?
From my understanding, that's a browser security feature that's stops you from using paths that resolve to your local computer rather than a specific url
Is it really worth it to integrate ReactJS with Django (not DRF)? Why do people even want to do that? Are there any benefits or something?
Imo templates are really good and easier to work with and get everything done, and afaik there isn't really any good reason to use React with Django, but I might be wrong so can someone maybe clear this out?
The point of react that it allows more complex frontend logic for your website.
One page could have a lot of smooth fast interactions all in one
They fulfill different jobs
They complement each other
Django does what react cant
We can't create single page apps when using django and react right
React can what dj cant
Why not
that's what i am asking, when using react with django, what benefits does it give over django templates?
We can create single page app with dj and react
Because each route is directed towards a single html file right?
You can do in this way
Or each dj app could spawn micro react app
That sounds very ineffectient tbh
It depends on logic site u need
Yeah but at the end, the question is what benefits does using React instead of Templates give?
we will 50/50 earnings
Dj templates are limited in js logic.
austt this isn't a web dev related question tho
i want to make a minecraft
yeah but how is that any better than multiple template routes?
can u help me make a web chat app?
sorry I can't
:incoming_envelope: :ok_hand: applied mute to @slender timber until <t:1627201327:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
!warn 831868294779633674 Please don't spam ping people when requesting for help, and re-read our #code-of-conduct. Consider this mute to be 3h long.
:incoming_envelope: :ok_hand: applied warning to @slender timber.
Because multiple state one page is not requesting every time your server. It is loaded one time to client and makes animation/fast transitions for client without repeated requests to server
The only requests it makes to server for limited pieces of rest json data if necessary
speed is the only thing then right?
Speed... And what is available in terms of js animations
you can use js in templates too tho
You can have literally a game paying in js for client
No one is stopping you from using js in html templates right
No one
But with react... You just use arrays of js libraries. More set of ready to use front tools
What kind of libraries would you need to use? Most of the time they are related to auth and routing which you don't need to care about in django, yes maybe lottie files for animations but quite sure you can do something like that with pure js too
Not sure. I saw react only from afar. I can say that they have that Redux library, that allows them to control state of multiple things going in front more easily
It makes them use Design Pattern State at library level I think
this thing mentions front tools for frontenders
Hey guys I need help is setting environmental variables in django.
yea i've read about it
trying to pass in the relative path gave an 404
same as anything else
<link href="C:/Users/01/Desktop/anon/app/templates/position.css" rel="stylesheet" type="text/css">
Anyone knows how can I open a url which return xml response and parse it in django
Why is my background not filling the whole screen? There is a bit of white space at the bottom, as seen in the image below and you can also scroll up and down and even right and left. In this website www.calcbot.ml the background is filled exactly according to the screen size
This is the page's code file
{% extends "layout.html" %}
{% block content %}
<h1 class="abspos" style="text-align:center;margin-top: 20px;color: white">SoLigh</h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/trianglify/1.1.0/trianglify.min.js"></script>
<script>
var colors = ['#17b023', '#c9bb49', '#17b023', '#adc947']
var pattern = Trianglify({
width: window.innerWidth,
height: window.innerHeight,
cell_size: 75,
x_colors: colors,
y_colors: colors,
stroke_width: 1.51
});
document.body.appendChild(pattern.canvas())
</script>
{% endblock content %}
requests can do the first bit. If i understand your question right its more of a python question and not django specifically so your options are quite open especially if its small and can be done relatively quickly.
Hey!!
https://docs.python-guide.org/scenarios/xml/#xmltodict
There is literally a library xml to dict.
After making request, make sure to use that
Hey!!! I want this check box outside the box but these 2 elements(The list and the checkbox) should be connected(because I should be able to make the opacity low when clicked the check box).I tried with position absolute and stuff like that but I couldn't make it
html
<html lang="en">
<head>
<link rel="stylesheet" href="styling.css" />
<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>To Do List</title>
</head>
<body>
<div id="main-box">
<h1 id="heading">To Do List</h1>
<p id="date">18-07-2021</p>
</div>
<form id="input">
<div>
<input type="text" placeholder="Add a task......" id="add_task">
<button type="button" id="add" href="#">+</button>
</div>
</form>
<div id="tasks">
<ol>Have To write Notes
<input type="checkbox" id="scales" name="scales"
checked>
</ol>
</div>
</div>
</body>
</html>```
CSS
```#add {
line-height: 0.1;
letter-spacing: 0em;
font-weight: 500;
font-style: normal;
font-size: 66px;
}
div ol {
position: relative;
background-color: rgb(0, 0, 0);
margin: auto;
width: 50%;
border: 1px solid rgb(255, 255, 255);
padding: 14px;
text-align: center;
margin-top: 80px;
color: azure;
font-size: 25px;
}
.scales{
position: absolute;
margin-top: 0px;
}```
Hello there , somthing I would know
is why we use post method when we delete token instead of use delete method
Anyone?
#🤡help-banana message
is the question to me???
Not just you for anyone who can help
why do you think so?
Because I do that
why are you asking someone else why you do something
Not this what I mean, I mean I learnt to do that
Thank you so much
Yes this I have seen but main problem is opening a url and getting XML
then use requests for humans
https://docs.python-requests.org/en/master/
Thanks will see this one
Hello, so I have a python script that has a while loop, prints like 4 outputs per sec,
now I need these 4 outputs to keep updating the html without the need to reload, so like the html keeps updating nearly in real time with the new outputs, any help?
I really can't figure it out
it's not wrong
but it is a bit odd
you will see APIs that use POST for more or less everything
there are restrictions on non-POST requests
that don't apply to POST requests
from flask import Flask
from threading import Thread
import string
import random
app = Flask('')
def sentence():
while True:
return random.choice(string.ascii_letters)
@app.route('/')
def main():
return sentence()
def run():
app.run(host="0.0.0.0", port=8080)
run()
I tried this which outputs a letter in a while loop, but the letter won't update unless I reload, also, it removes the previous letter...
How do you make mp3 file play in the background as soon as you land on a page?
That's the issue, since the browser blocks any requests that don't resolve to a url
this is considered a BIG "don't do it" thing
in 2021
Instead, you'll want to use to use the static tag for the template language you're using
You'll want to move your file out of the templates directory and into a directory called static
And then the template language you're using should have a tag for static urls (but if that's just regular html, you'll want to use a relative path rather than one that compares to the root of your computer)
Can anyone help me with html, I don't know how to put an image on the website, that's on my computer. So I have the file saved in my computer but I tried anything and nothing works, it just shows this little image not found thing on the website.
this is how it looks like, I tried putting it in a folder in visual studio and stuff but nothing works
Try passing in the absolute path
any help?
try putting it with ./stars.png or ../stars.png (the 1 dot means that the image should in the current folder/path while the 2 dots mean that image is 1 level/directory above I think) the problem is either the url, the image extension (check if its actually png or jpeg if you don't use the vscode autocompletion and write it manually) or the image is not broken
@next comet thank you so much, it works
haha no worries, glad i could help
don't really understand this part
What library are you using?
Django? Flask? FastAPI?
Any Help please?
You have to use JavaScript to pass data or info without reloading
Can you give an example please?
What do you use on your frontend?
It's not a complicated website, it literally just has a button to start the script, and a box to show the output
that's it
I am using flask for the deployment
Well you will need some js for that as the other user said if you want to update content without page reload. You can also have auto reload with meta refresh but that might not be what you want.
JavaScript is used to update a web page without reloading the page
I have some basic js and DOM knowledge, but do you have some sorta example on how I can apply it? via Stackoverflow for example
and how do I connect it with my py script?
Ok let me see if I have something
I don't have much experience with JS. Hope someone else can help you out
Maybe this can help you, https://flask.palletsprojects.com/en/2.0.x/patterns/jquery/
Aight ty
I'm trying to make a video calling website and i have never used python to make a website
heyall
anyone here experienced in django admin?
class Order(models.Model):
class Meta:
ordering = ('-date_created',)
class Status(models.IntegerChoices):
PEN = 0, "PENDING"
PAI = 1, "WAITING VERIFICATION"
ECD = 5, "BAD ESEWA CODE"
OOS = 4, "OUT OF STOCK"
DEL = 2, "DELIVER"
COM = 3, "COMPLETE"
profile = models.ForeignKey(Profile,on_delete=models.CASCADE,related_name='order',null=True)
status = models.PositiveSmallIntegerField(choices=Status.choices,default=Status.PEN)
date_created = models.DateField(default=datetime.date.today)
ship_to = models.ForeignKey(Address,on_delete=models.CASCADE)
email = models.EmailField(null=False)
phone = models.CharField(max_length=15,blank=False)
transaction_code = models.CharField(max_length=12,unique=True,blank=True,null=True)
class Address(models.Model):
country = models.CharField(max_length=64)
district = models.CharField(max_length=64)
municipality = models.CharField(max_length=64)
ward_no = models.PositiveSmallIntegerField()
street = models.CharField(max_length=256)
i have this two models and i want to unpack the 'ship_to' field in the admin page
i tried using inline admin but django throws an error saying it needs a foreign key in the address model
currently im limited to
well i managed to do it using readonly fields and calling individual functions
class OrderAdmin(admin.ModelAdmin):
model = Order
inlines = [OrderItemsInline,]
list_display = ['get_email','id','email','phone',
'transaction_code','status']
list_filter = ['status']
search_fields = ['profile__user__email','id','email','phone']
readonly_fields = ('profile','ship_to','get_country','get_district','get_municipality','get_ward_no','get_street')
fieldsets = [
('General',{'fields':('profile','status','date_created')}),
('Details',{'fields':('email','phone','transaction_code',)}),
('Delivery Address',{'fields':('get_country','get_district','get_municipality','get_ward_no','get_street','ship_to')}),
]
def get_email(self, obj):
return obj.profile.user.email
get_email.admin_order_field = 'user'
get_email.short_description = 'Profile email'
def get_country(self,obj):
return obj.ship_to.country
def get_district(self,obj):
return obj.ship_to.district
def get_municipality(self,obj):
return obj.ship_to.municipality
def get_ward_no(self,obj):
return obj.ship_to.ward_no
def get_street(self,obj):
return obj.ship_to.street
get_country.short_description = 'country'
get_district.short_description = 'district'
get_municipality.short_description = 'municipality'
get_ward_no.short_description = 'ward_no'
get_street.short_description = 'street'
like so , how bad is it?
Hi, how can I block access to a specific page (exmpl.com/profile) to those who have not yet logged in (python and Django)
If you're using Class based views you can use LoginRequiredMixin
its this import from django.contrib.auth.mixins import LoginRequiredMixin
you use it like so:
@native tide
flask
Take a look at this: https://flask.palletsprojects.com/en/2.0.x/tutorial/static/
okay
and if you're using function based views you can >
def index(request,*args,**kwargs):
if request.user.is_authenticated():
messages.error(request,'You need to login')
return redirect('app:login') # Redirect to login page
else:
return render() # Your page here
yes im using this, i tried the code but it appear an error for if request.user.is_authenticated(), the error is 'bool' object is not callable
i find a decorator to use in this case
@login_required(login_url='/login/')
def Profile_user(request):
return render(request, "profile_user.html")
imports
from django.contrib.auth.decorators import login_required
class Post(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
caption =models.CharField( max_length=100,blank=True)
history = HistoricalRecords()
video = models.FileField(upload_to='videos/',blank=True)
tagged_people=models.ManyToManyField(User,related_name='tagged_people',blank=True)
like_people=models.ManyToManyField(User,related_name='like_people',blank=True)
posted=models.BooleanField(default=False)
created =models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(auto_now=True)
class ReportPost(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
description =models.CharField( max_length=100,blank=True)
created =models.DateTimeField(auto_now_add=True)
post=models.ForeignKey(Post,on_delete=models.CASCADE)
def __str__(self):
return self.post.user.username +'::' +str(self.description)
I want to get the Posts which are not in ReportPost model pls tell me queryset for this
why is it formatted so disgustingly?
Instead, I would give Post and ReportPost a one-to-one relationship (as one reported post corresponds to one post). Then, I would add a BooleanField called reported to the Post model. I would override the .save() method of the Post model, or add a post_save signal to ReportPost, which will check if there are any objects on the other side of the one-to-one relationship, if so, reported=True.
Then you can just filter all objects by the reported field...
request.user.is_authenticated, .is_authenticated is a property of the User model, not a method.
it returns a boolean, which isn't callable
finally made my first flask app after a month! pls check it out lmfao
address: localhost:8000 or 127.0.0.1:8000
you know that's a local address, right
on insta, the message is in a <span> tag while inspecting, however, I am able to use selenium xpath to find the message but not the latest one, is there a way that i can use time to filter out the message to find the latest one?
is it possible for me to store all the message into a list than use list[:-1] to find it?
that's local address, only your computer can access it
i am working on a flask web app with my firends and we needed a way to update graphs on our dashboard page so they made a dashboard.py file. Is there any way to implement this file into my flask webapp. Specifically i want to go to this dashboard page once the user has logged in. But i have no idea on how to do this can someone help? thanks!
But they are not in one 2 one realtionship because Any user can report any post (maybe two user reports same post ) I have planned not to show the reported post to that user
If not possible I will literate through the objects
can anyone help me with this
Js can help you out
how so?
Can you share a code
And did.you are using html css javascript in frontend
what part of it do you want
i am using html for the templates
i think i understand what you mean. I just found out that its possible to embed interactive files with javascript
Then cools and you using chat.js library of Javascript you just have to send the a request every 1 min to database and update the graphs
Or maybe a button to update graphs
i c
we aren't updating them particularly just trying to make the grpahs more interactive
can we interact with the grpahs with chat.js? like zoom in and pan over different sections
@stark tartan can i do the same thing with plotly graphs
from defaults import server_url
import asyncio
import socketio
import json
sio_client = socketio.AsyncClient()
# Main Connection
async def main():
await sio_client.connect(server_url)
await sio_client.wait()
def run_sio_client():
asyncio.run(main())
# Default Events
@sio_client.event
async def connect():
print(f"Connected!")
@sio_client.event
async def disconnect():
print("Disconnected!")
@sio_client.event
async def sid(sid):
print(f"MY_SID: {sid}")
``` ```python
from src.helpers.sio_client import run_sio_client, sio_client
import threading
import time
async def test_ping():
await sio_client.emit("test_ping")
t1 = threading.Thread(target=run_sio_client)
t1.start()
while not sio_client.connected:
print("NOT CONNECTED, Trying again...")
time.sleep(1)
test_ping()
print("REACHED HERE!")```how do run `test_ping()` ?
I want to connect to socket.io server and use `sio_clien`t to emit events on some logic
OUTPUT
NOT CONNECTED, Trying again...
NOT CONNECTED, Trying again...
NOT CONNECTED, Trying again...
MY_SID: nNuJg3vJzdkADd71AAAN
Connected!
D:\Coding Stuff\UpWorkStuff\LinkedInDelivery\li_worker\run.py:16: RuntimeWarning: coroutine 'test_ping' was never awaited
test_ping()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
REACHED HERE!```
script just hangs after this
Yes
I haven't learned flask yet but I have a question, if I upload an image in my flask instance and post that link on discord , can discord render that image?
Yes but your application must be hosted so that discord can get image by url
Ah yes ofc
Ofc ??
'of course'
I don't use social media much🥲 🥲 😅
Oh no it's fine .. we've all been there 🤗
how do I make this symmetrical?
its the text length that does this, if they are all the same length in characters they will be equal
but they aren't so how else would I fix this?
heyho my friends i have a problem with my flask app
it won't run because of an error that i can't find
my server says the error is in line 44 but there is no obviews error with the code
the app runs fine in pycharm
Hey @swift dune!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
You shouldn't try to format the address of your template as a string. Just write your template name hard-coded like "themes/yourfilename.html"
in the html file ?
i downloaded a free template from internet, i want to change the theme color how can i do it
css
ig
it was working, after the migrations it wont work anymore
Looks like there is a problem in serving static files
literally the dashboard is working, only the homepage get this errors
ok i fixed
im dumb i didnt see that the folder with css and js was outside home folder
anyone can tell me how can i debug django tests in vscode, i tried to search in the net but nothing seems helpful and explanatory
I get this.
@app.route("/")
def home():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
``` That's the code about the website
in my bot file
Hi, I'm having problem with understanding Django's filter is_safe param in the @register_filter decorator.
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#filters-and-auto-escaping
will replacing whitespace with "+" sign in string be considered always safe and can be marked with is_safe=True in the decorator?
and why do we even bother marking it with is_safe? Just so that Django doesn't have to do unnecessary work and escape output if we know it will be safe?
@stark tartan a One tovOne relarionship between Post and ReportedPosts
why when I modify the site's css file, nothing changes?
i have to reload somethin? (i tried to rerun the server but nothing)
ok i fixed
by opening it on incognito
(the changes didnt appear for the cache of the site maybe )
Hey everybody, i am trying to setup Nginx for my server. Is UWSGI necessary?
You don't have to use uWSGI if you want to go the WSGI-route (which is the most common route). Gunicorn is also a popular option.
What is the difference between them?I don't know much
I am a beginner in server deployments, i don't know anything related to WSGI and Gunicorn
Only thing i know is NGINX helps to modify some protocols for server requests
NGINX does not "know" how to talk to a Python-application. Django supports WSGI, which is a standardized way to talk to Python web applications. uWSGI and Gunicorn do that "translation step", so you get something like client <---> Nginx <---> uWSGI <---> Python app
Sebastiaan can u help me?
@native tide Your question does not seem to relate to this channel. I think it's best to open a help channel (see #❓|how-to-get-help) or to find a topical channel that does firt your question.
What Frontend i use with Flask?
So wsgi.py does the job that is necessary ? I wouldn't face security issues right?
My bad am sorry
wsgi.py provides the parts that uWSGI/gunicorn can call
So, it's not something NGINX knows how to talk to on its own
What kind of front-end do you want to use?
I am asking because i face with this problem whenever i need to configure something with UWSGI
sudo service uwsgi start
Job for uwsgi.service failed because the control process exited with error code.
See "systemctl status uwsgi.service" and "journalctl -xe" for details.
I think i will try gunicorn. Thanks for the help
Which Works Best With Flask..... HTML, CSS, JS or React?
There's no single thing that works best, although flask would probably play a slightly different role if you use a full-fledged front-end app like react/angular