#web-development
2 messages · Page 214 of 1
for my opinion, nothing comes close to django admin interface. if u understand u see the beauty in easiness it makes :)
I don't know what get_engine() is but it's expecting an argument
I think Table is used for a many-to-many relationship: https://docs.sqlalchemy.org/en/14/orm/basic_relationships.html
Thanks! I'll check that link
I know, but idk why. Any tutorials or documentations has similiar codes and no error
Share an example you are trying to follow?
If you don't get an answer here, I would try #discord-bots
hello sir, can i ask somequestion about django4 in here ?
How do I share my data(specifically data stored in python objects) across multiple post routes in flask? Do I need a database and user-login feature kind of system to implement this? Or is it also possible to build this kind of feature for a guest user i.e. without keeping track of who the user is? I am currently using global class to store the data and share it across routes, but I think it works only for one user. It won't work if more than 1 people start using my web app coz data exchange might take place. How do I solve this?
hey guys, bit of a weird one, spring (boot) or asp .net. I want to get hired and i dont have a degree, which framework is more liked and has a greater want
Hi! I'm an intern react front end developer. I want to get started on back end development too. What should I do
Should I use python/django/flask or the typical node. Js?
depends. if you want to continue using js, go with node js or feathers js but if you want to use python and create backend easily with basic security then go with django
I do want to experiment with django...
if you are going to choose django, you won't be disappointed
Can you suggest some resources to learn and implement django?
traversy media's course is good. here's the link https://youtu.be/PtQiiknWUcI
Build a discord-like application with Python Django. Visit the finished application at https://studybuddev.herokuapp.com/
Get The Full Django Beginners Course:
https://dennisivy.teachable.com/p/django-beginners-course/?product_id=3222835&coupon_code=BRAD
Use promo code BRAD for 50% off
Dennis Ivy YouTube Channel:
https://www.youtube.com/c/den...
Dennis Ivy is great and there is another channel you might want to check out, it's Just Django
Hi i am facing an error in django the model is working fine in localhost but when we deploy it ton heroku it throws an error
some one help me
Hey @digital thorn!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Hey @digital thorn!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
I'm looking for recommendations on which framework to use for a simple app with one endpoint, which will be deployed in multiple VMs (worker machines). We are currently using Flask, and planning for some major refactoring, so just want to checkout other options. Any suggestions?
if web based app maybe angular and react with node.js
when I try to run my local server It wont run anything just download some files it was working yesterday i dont know what happened suddenly.
the problem can be in your home html file and not in server
i have done every thing I was about to deploy it but thought of checking the site for the last time and then this happend
can you show me your base.html and home.html
does fetch api work in brave?
A database is the normal way
You'll need to do more troubleshooting or provide more information but I would guess you're not properly connecting to the correct database or not migrating your data/schemas correctly. Maybe try a help channel #❓|how-to-get-help
Hell.
I am Django developer.
I want to find some jobs here.
hey guys me and my friend have some ideas about web application we are thinking of making one so if anyone interested in joining
pls contact me (pls dm me personally)
We originally need people who work on python,HTML5,css and JavaScript
(This is not a Job, and no one is getting paid )
Pls dm me personally
*This is not a paid job, but I am more than happy to add your name as credits in the app, if a noticeable contribution is made . Please direct message me if interested. Thank You!
Pls dm me if you know anyone who is ready to help
hello friends...I am trying to write a text inside <p> </p>
i'm working with selenium..
i have searched a lots...couldn't find the proper implementing function
please can someone help !
<div>
<span class="placeholder">Join the discussion…</span>
<div class="textarea" tabindex="0" role="textbox" aria-multiline="true" contenteditable="PLAINTEXT-ONLY" data-role="editable" aria-label="Join the discussion…" style="overflow: auto; overflow-wrap: break-word; max-height: 350px;">
<p><br></p>
</div>
FastAPI for rpc, Django for common websites, Flask - omg just forget it.
Remote procedure call server. https://en.wikipedia.org/wiki/Remote_procedure_call
In distributed computing, a remote procedure call (RPC) is when a computer program causes a procedure (subroutine) to execute in a different address space (commonly on another computer on a shared network), which is coded as if it were a normal (local) procedure call, without the programmer explicitly coding the details for the remote interactio...
Any good source to learn React Js for beginners ??
They have pretty good official documentation. Just google it.
Is there a function for performing number formatting (e.g. thousand separator) like f"{number:n}" without having to change the locale globally and then reset it again afterward for every request?
hi guys, need a bit of help with this project im trying to scrape data for, this is my code, for some reason, im getting attribute error for navigablestring, any help would be appreciated:
PageURL= "https://www.hltv.org/stats/matches?startDate=all"
SiteURL= "https://www.hltv.org/"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36" }
response= requests.get(PageURL, headers=headers)
soup= BeautifulSoup(response.content, 'html.parser')
tbody= soup.tbody
trs= tbody.contents
teams= {}
for tr in trs:
for td in tr.contents:
print(td)
print()
can you show the error? and where exactly it's crashing?
the error is:
AttributeError: 'NavigableString' object has no attribute 'contents'
I did then also error occurs
What do you mean by "do a comment" with Selenium? Are you trying to extract a certain attribute?
in fact it is an input bar where i can write in it
Is this what you're looking for? https://www.tutorialspoint.com/how-to-send-keyboard-input-to-a-textbox-on-a-webpage-using-python-selenium-webdriver
How to send keyboard input to a textbox on a webpage using Python Selenium webdriver? - We can send keyboard input to a textbox on a webpage in Selenium webdriv ...
i have tried a lots of methods and also jumped in between different functions and selecting the different possible elements between the div classes 😛
still not working 😦
Show an example of what's not working?
Traceback (most recent call last):
l = browser.find_element_by_class_name("textarea")
File "C:\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 564, in find_element_by_class_name
return self.find_element(by=By.CLASS_NAME, value=name)
File "C:\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
'value': value})['value']
File "C:\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".textarea"}
(Session info: chrome=97.0.4692.99)
Process finished with exit code 1
And the code that gives you that error?
l = browser.find_element_by_class_name("textarea")
l.send_keys("Selenium")
#send keyboard input
l.send_keys(Keys.RETURN)
NavigableString objects do not support the .contents attribute, as they can't contain anything. As Tag objects do, perhaps consider using isinstance to check the object type and only call .contents if the object evaluates to Tag.
Yes because tr is of type Navigablestring and it doesn't have an attribute called contents
Hey there, anyone got hands on permissions? Working on webapp/mobapp and it's first time dealing with permissions. API is done via GraphQL -- Django Graphene.
I got my user permissions and admin permissions, but how do I define anonymous user permissions?
Did you load the right page first? you can print(browser.page_source) to be sure
Damn for skipped again
Hi! How can i replace this "Password (again)" for "Repeat your password" in django allauth??
how do i get jinja to recognize that variable
it's inserted like this
"defaultContent": '<span class="edit_btn"><a id="edit_pencil" href="{{ url_for(\'update_details\', T_Number=vehicle.T_Number)}}"><i class="fas fa-pencil-alt"></i></a></span>'
Don't escape the single quotes
in include urlconf_module = import_module(urlconf_module)
from django.contrib import admin
from django.urls import path, include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("Folder.urls")),
path('/dashboard', include("dashboard.urls"))
]
urlpatterns += staticfiles_urlpatterns()```
i am out of ideas again !!
can u check it from ur side please
https://bscscan.com/token/0xba2ae424d960c26247dd6c32edc70b295c744c43#comments
in the comment section...try it if it working from ur side...it might be that i am having a problem! dunno where :S
The first thing I notice is that the comments section takes at least a second or two to load. So you need to wait element_to_be_clickable or something like that. https://selenium-python.readthedocs.io/waits.html
Thank you
i'm working on a django site and updating some of the images under static
for some reason though refreshing the browser doesn't show the new updated images
is it a cache thing?
i'm running it in docker
i'm able to display new images i've created fine
ah yes it was a cache thing
hey guys me and my friend have some ideas about web application we are thinking of making one so if anyone interested in joining
pls contact me (pls dm me personally)
We originally need people who work on python,HTML5,css and JavaScript
(This is not a Job, and no one is getting paid )
We are thinking it to be some sort of a teaching app
Where we teach people, well right we will be teaching about only 3 computer languages
HTML5, CSS, PYTHON and maybe in future we will add a video feature in the web app and be teaching other languages as well.
django-channels question,
I have a ChatGroup model and when a Message is sent in a chat group how do I dispatch the event to all users who are in that chat group?.
Like the frontend will connect to a single endpoint like http://127.0.0.1:8000/api/ws and it'll receive an event when a message is sent in every chat group the user is in
depends on if you are using a pull vs push approach.
In a pull approach, you may have to poll based on the latest timestamp. In a push approach, your servers would require the ability to push updates to the interested clients
That could become quite complex depending on the scale of the system
i need help can some one help me with this
does the table articles_authorarticles exist?
because the error complains it doesn't exist
no
yes i know but when i migrate it not creating tab;e
this the table
sqlite3 is better or mysql mongodb better for django ?
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="utf-8">
<meta name='viewport' content="width=device-width", initial scale=1.0">
<title> </title>
</head>
<body>
<div class="links">
<div class="links_items">
<a href="#" target="blank">Github</a>
</div>
<div class="links_items">
<a href="#" target="blank">Instagram</a>
</div>
<div class="links_items">
<a href="#" target="blank">Website</a>
</div>
<div class="links_items">
<a href="#" target="blank">Whatsapp Group</a>
</div>
<div class="links_items">
<a href="#" target="blank">LinkedIn</a>
</div>
</div>
</body>
</html>
Can somebody show me the error, its not displaying on my browser
I corrected that now but its still not appearing on my browser
anyone here rn?
I have a basic doubt regarding the active status of a certain button
currently using css and html
the "home" part
this is the html part
this is the css part
why is the home's written part not visible in black
and why is the whole box not white
try to drop the table and then create a new table with same name. Then migrate all the migrations from django, see if that works
Anybody knows what this selected effect is known as ?
CSS ?
yes, but nvm I got it
hi guys , quick question, if i want to parse through every page with this tag:
from this baseurl:https://www.hltv.org/stats/matches?offset=0 could some one point in a general direction how to?
You can use beautifulsoup to parse the page in python, and you can increase the offset by 50 in every iteration to get new pages of data
yea im using BS to scrape, so it would be like, base url= the one i linked, and then parseable url would be 'https://www.hltv.org/stats/matches?' +str{offset} inside a loop? im kinda confused how would do it
ah fk sec i'll update that
yeah that seems reasonable, you just have a loop where you increment the offset by 50 in reach iteration
the offset is a query parameter, so you have to add it at the end of the url with ?offset=200
so like...
for offset in range(0,60000):
.
.
.
im kinda confused with what to do inside
or would it be, offset+50
give me a second, I'll get to my pc and be more helpful 😀
lol sure
claimed avocado
https://magic-name.herokuapp.com/
hey guys check this djnago website it shows your system information and ip information
please give feedback how i can improve it pleasse
Are there other services like Heroku where I can easily deploy a Flask app?
Totally different use cases. For a public facing web app with any significant traffic, SQLite probably won't cut it. Mongo is NoSQl so it works pretty differently. If you want a SQL database that can scale up, Postgres would be my first choice but MySQL is fine if that's what you're used to
Heroku is probably the best for small projects. PythonAnywhere is another option but I've not really used it. Then there's always the big three (AWS, Azure, Google)
@golden bone Thanks. I’ll stick with Heroku. I wish there was a free option that didn’t put the app to sleep after a period of inactivity.
Yeah, the big three all have a free tier, but you'd probably have to pay after the trial period
oh thanks, how can I implement the push approach using django channels?
Because I will have to iterate through all connected users and check if they are in the chat group
Right now this is what I got ```py
@receiver(post_save, sender=Message)
def new_message(sender, instance, created, **kwargs):
channel_layer = get_channel_layer()
if created:
chat_group = instance.channel.chat_group
for member in chat_group.members:
async_to_sync(channel_layer.send)(
f"User-{member.user.id}",
{
"type": "chat_message_create",
"payload": MessageSerializer(instance).data,
},
)``` and the data doesn't get dispatched throughout the websocket
Does anyone here know how to use the django frame work
Don't ask to ask, just ask
If anyone is good with Django deployments on Heroku, this discussion has moved to #help-chestnut and I'm not much help
What does the "Learn More" link say? And how recently did you change those DNS records?
Hi all, I have a fairly busy dashboard page in a Django app that takes too long to load. Some of the items can be downloaded "asynchronously", meaning as and when available after the rest of page has otherwise loaded and the user started interacting with it. Any suggestions on how to achieve that? Many thanks
Heya everyone, django question:
I have this modal with a form inside:
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog">
<form action="{% url 'reject-listing' listing.pk %}" method="post">
{% csrf_token %}
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">{% translate "REJECT_POST" %}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"
aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label for="message-text" class="col-form-label">{% translate "REASON" %}:</label>
<textarea class="form-control" id="reason"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-secondary" data-bs-dismiss="modal">{% translate "CANCEL" %}</button>
<button type="button" class="btn btn-warning">{% translate "REJECT" %}</button>
</div>
</div>
</form>
</div>
</div>
that am trying to run, but it's giving me this instead in the browser:
<div class="modal-dialog">
<form action="/en/reject/13" method="post"></form>
....
Any idea why this is happening?
oh
I do, I'm working on a project in django, let me know what you need
Not an expert but have used django for some time. ask away
@honest dock Familiar with AnonymousUser permissions? Which api are u using? Rest or GraphQL?
Can someone here help me with bs4?
Im making a crawler .Not sure how closely that is related to this channel lol
Okay. Don’t really need a whole channel. Just a question about targeting. I need to target a part of a class since the class itself dictates the rating.
@gentle ingot That is the whole purpose for a channel. So they can give you further information about the situation.
No I understand that. But like. I feel that’s a simple yes abs no and would feel bad for taking a channel from@someone lol.
Not going to lie, I have no knowledge about bs4; so I can't help you.
@gentle ingot Maybe you can ask someone else
Thats okay. thanks for the channel suggestions. heading there
@gentle ingot Glad to help
Assuming:
- You mean that you are using websockets between the client and server
- Different clients for the same group chat may be connected to different servers
- There is no concept of federation
You could either:
- have your server periodically check their DB/cache (ex: redis) for new messages for their connected clients
- listen on a kafka/pulsar/rabbitmq topic for update notifications. Note there could be additional measures to filter out unnecessarily traffic
- use a layer of indirection with some proxies where a group chat is "hosted" and all the clients part of that group chat connect to and then channel the updates through there. But it's more appropriate for real time use cases, and not something I would go into right off the bat due to the added complexity
:incoming_envelope: :ok_hand: applied mute to @native tide until <t:1643571137:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
class myFormView(FormView):
template_name = 'myTemplate.html'
form_class = myForm
success_url = "/blahblahblah"
def form_valid(self, form):
email = form.cleaned_data['email'] # <--- Add this line to get email value
return super(myFormView, self).form_valid(form)
why is super(myFormView,self).form_value(form) is returned?
what does it do?
I'm not that strong with Django but share the code where your dashboard endpoint is defined? Do you have other endpoints that are working?
where
problem is
there ```def main(request):
return HttpResponse(request, "main.html")
def dashboard(request):
return HttpResponse(request, "dashboard.html")
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("Folder.urls")),
path('', dashboard),
]
urlpatterns += staticfiles_urlpatterns()```
dashboard/ isn't part of your urlpatterns. I think it would need to be unless admin/ is the endpoint you're really looking for
Basically, each time you change the structure of your database, you want to track that there. This way you can reverse or redo the changes if you need to
I could use some help with fastapi if anyone can
It's an issue with websockets, it worked fine before, now there's an issue for some reason
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/home/lafftar/.local/lib/python3.9/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 203, in run_asgi
result = await self.app(self.scope, self.asgi_receive, self.asgi_send)
File "/home/lafftar/.local/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
return await self.app(scope, receive, send)
File "/usr/local/lib/python3.9/dist-packages/fastapi/applications.py", line 212, in __call__
await super().__call__(scope, receive, send)
File "/home/lafftar/.local/lib/python3.9/site-packages/starlette/applications.py", line 119, in __call__
await self.middleware_stack(scope, receive, send)
File "/home/lafftar/.local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 146, in __call__
await self.app(scope, receive, send)
File "/home/lafftar/.local/lib/python3.9/site-packages/starlette/exceptions.py", line 63, in __call__
await self.app(scope, receive, send)
File "/home/lafftar/.local/lib/python3.9/site-packages/starlette/routing.py", line 659, in __call__
await route.handle(scope, receive, send)
File "/home/lafftar/.local/lib/python3.9/site-packages/starlette/routing.py", line 318, in handle
await self.app(scope, receive, send)
File "/home/lafftar/.local/lib/python3.9/site-packages/starlette/routing.py", line 77, in app
await func(session)
File "/usr/local/lib/python3.9/dist-packages/fastapi/routing.py", line 263, in app
solved_result = await solve_dependencies(
File "/usr/local/lib/python3.9/dist-packages/fastapi/dependencies/utils.py", line 465, in solve_dependencies
response = response or Response(
File "/home/lafftar/.local/lib/python3.9/site-packages/starlette/responses.py", line 50, in __init__
self.init_headers(headers)
File "/home/lafftar/.local/lib/python3.9/site-packages/starlette/responses.py", line 77, in init_headers
and not (self.status_code < 200 or self.status_code in (204, 304))
TypeError: '<' not supported between instances of 'NoneType' and 'int'
INFO: connection open
INFO: connection closed
This is the error, no idea why it started popping up
code is very simple:
client
import websockets
from websockets.legacy.client import WebSocketClientProtocol
ws_link = 'ws://0.0.0.0:1337/'
async for ws in websockets.connect(ws_link, timeout=1):
ws: WebSocketClientProtocol
server
from fastapi import FastAPI, WebSocket
@app.websocket('/')
async def receive_recap_tokens(websocket: WebSocket):
log.info(websocket.client)
await websocket.accept()
cmd to run server
uvicorn api:app --host 0.0.0.0 --port 1337
any help is appreciated
nvm me, was just a version issue
What kind of work do python backed junior Django
so I am making my first website using django. It's going good but I am having this overflow issue.
Basically a long 'word' overflows out of the div. I searched on internet and used stuff like overflow-wrap, break-word but they don't seem to work.
Any help is appreciated.
here is the html just in case.
{% extends "blog/base.html" %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{ user.profile.bio }}</p>
</div>
</div>
</div>
{% endblock content %}
I'm thinking maybe you need to play with the width of the div https://www.w3schools.com/css/css_max-width.asp
word-break: break-all;
this worked. and why tf I didn't try this before :(
though thanks
👍
Different clients for the same group chat may be connected to different servers
This is a project which I am making for fun 😃
there will only be one server
then the same ideas but in the memory of your server 🙂
Yay, I made the deployment of my project to prod level servers
https://shapevpn.com/
Can anyone score it, and to say anything you notice about it?
Basically I need a third person look what could be missing. My point of view is too subjective to notice things anymore
Short description: This website helps to set up your own VPN server for easy usage on PC or mobile.
You will have an encrypted internet connection, which prevents data leaks to Internet Service Providers or any other third parties.
And your internet location would be shown as the location of the VPN server.
You made this?
From zero to production
Congratulations my dude
I was architect
I was backend Dev
I was infrastructure Dev
I was Frontend Dev
Overall my grade as someone who isn’t very knowledgeable is that you did a great job
The FAQ are a nice bit
And I enjoy the idea
Rest of the site is nice too
It’s just a nice, simple, and still detailed website
That’s all I got
Thanks ;)
It looks very nice @inland oak does it use python for the backend? I mean it's kinda obvious tho lol
yeah, Python: Django + Celery
Cool!
What are you using on the frontend?
Is it django rendering templates or something like react?
How can I share my codes in color like this?
Vue.js 😉 CSS is just augmented by SASS
hi guys, need short help, I have a url: html https://hltv.org/stat/matches
now i want to that url parse other part of it which is stored inside a dict, how can I do that
btw claimed #help-cookie
Hello, Ive seen some websites have this in their HEAD part. for discord embed stuff
How'd I add it to a starlette Response
to these
I tried messing around with the headers kwarg but no luck
Starlette uses Jinja 2 Templating, perhaps to write in the template

Can't access it?
Wonder if it's my work net that's the problem.
Ah, yea it is.
More nitpicky stuff, but on mobile, I would probably center the icons and perhaps use a black background behind the "we aren't vpn" + icon div for some more contrast.
noted 🤔 thanks
Hello, could anyone here help with an error I'm getting in Django?
I'm saving some rather long reddit comments to my psql database. They're stored in a TextField with a unique = True constraint
(I'm relatively inexperienced and I didn't want to accidentally add duplicate values to my database).
Trouble is, Django is now throwing this error when I run:
index row size 2808 exceeds btree version 4 maximum 2704 for index "saved_posts_toplevelcomment_contents_key" DETAIL: Index row references tuple (2,28) in relation "saved_posts_toplevelcomment". HINT: Values larger than 1/3 of a buffer page cannot be indexed. Consider a function index of an MD5 hash of the value, or use full text indexing.
I've had a look online and it seems that psql adds an index for the unique = True constraint that I've added.
I'm not sure how to solve. I just want to make sure there are no duplicate values. Should I add some logic in my view to this effect and just remove the unique constraint?
maybe someone could help me around, how can I concatenate the data I parsed using scraping functions into a DF?
Hello, I have a machine learning model which I converted as a Rest API using Django rest framework. Now I want to distribute the API to users but how can I authenticate and limit the requests by the users by allowing them to interact the api using an api key?.
I would think that the user would need an account that is associated with the API key to start off with.
So each user has a unique API key.
Then you could just control everything with user authentication as usual (whatever backend web framework you use).
I'm not sure the best way to throttle though, as you would need a way to keep the current usage somewhere. If it's just how many times per day, perhaps you could just have a field on their user account that counts how many times they access, and reset it at a certain time of day or after a number of hours.
Thanks @dense slate How can i give every user a new api key when they register with a new account in Django rest framework?
Did you mean using JWT?
You could generate a new key on signup. I'm not sure what you're asking beyond that.
Thanks
if someone could check out #help-falafel id appreciate it 🙂
i have error
<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">
<script src= '/static/js/index.js'></script>
<link rel="stylesheet" href="{{ url_for('static', filename='menu_page.css') }}">
<title>Document</title>
</head>
<body>
<button onclick="addToScore(1)"></button>
<p>Score: <span id="score">0</span></p>
<script>
var score = 0;
function addToScore (amount) {
score = score + amount;
document.getElementById ("score").innerHTML = score;
}
</script>
</body>
</html>```
looks like skill issue tbh.
it's only for super l33t coders, no worries, keep going at it and your code will get colored too
kidding,
"""
```py
"""
well, that's tough to show
put the code in between the three backticks
i am confused about class based views in django and how over wridden functions work
https://docs.djangoproject.com/en/4.0/ref/class-based-views/base/
Base views | Django documentation | Django
for example when u look at the function dispatch i dont understand what its doing
Hello, can anyone explain me one thing about Django?
My problem is that in production (I am using App Engine(Google Cloud)) my templates load old staticfiles.
I am wondering why this happens.
settings.py
STATICFILES_DIRS tells me where to search for static files that are not tied up to a specific app.
STATIC_ROOT is the path where we store the static files of every app once we run python manage.py collectstatic
STATIC_URL is just a prefix for static files.
Why in localhost it shows me the updated files and why it doesn't happen the same in production?
Running with gunicorn? Is that a thing in your production environment?
I wonder if you have a cached version showing.
I am not
I am right now checking
it doesn't even work in localhost now if I use the remote database connection
it just shows me a file that I don't have in my Django project folder
that file has been edited
but I see the older version
it's like when I render the template, it takes the files to another place
You sure you edited the correct file?
yes I did
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'website/static'),
)
it means that when the template render, it looks for files in /staticfiles once I run python manage.py collectstatic
the file I made changes to is correct in /staticfiles
but it's not the same that I see using Development Tools when the website runs
/staticfiles/stuff.css
Development Tool
the structure also looks clean
there's no way
I am wondering.. is it possible that it search for the files in Google Cloud Storage?
But there's not a bucket that contains those files, so, where is it taking them from?
I am completely sure that it doesn't look for the new files when I upload the website, because, as I said, both website/static/website/stuff.css and staticfiles/website/stuff.css are correct
that's just like it takes them from another place, but the url in HTML it's correct as well, is just the file that's different
What's it showing incorrectly? The CSS or the template itself?
every static file that I edit
css, js, html
it just stopped working
I have been using a Google Cloud instance that I replaced by a new one
but instances doesn't get involved with buckets
are your dirs correct? shouldn't there be / at the end?
everything's correct
it worked until yesterday
without reasons, it started doing this
@dense slate is it Gunicorn the tool that creates staticfiles.json file that contains all the staticfiles paths?
or is it WhiteNoise?
nothing happend3s without a reason
Gunicorn uses workers to serve your pages to visitors.
But you need to restart it when you change files.
Probably not the case if you didn't set it up yourself.
I think that there's a problem with myself then
when I do
{% load static %}
and use
{% static 'website/stuff.css' %}
is it looking in "staticfiles/website/stuff.css" or in "website/static/website/stuff.css"?
do I have to store the statifiles in another place in production? Can't I just do like I am doing?
I mean, if Djagno uploads the files to "staticfiles" folder, why do I have to upload then to another place?
I also added the right settings in urls.py
you can print the base_dir locally and look at your terminal to see what the directory should be/is
that way you can rule out if it's a directory issue
You put files in static, and collectstatic puts them somewhere else on its own.
You don't put them in two places manually.
I want to check what's this output in production
it could give me some informations
ah ok
just give me some time to check for google cloud log's output
let's see
the output looks clean
i just tried to delete all index.html content 😂😂
the page just shows!
that doesn't even make sense
I am running in local, in local database
that's up to Django
that doesn't make sense
I FOUND THE PROBLEM
Using DEBUG = True saves the changes, using it to False does not
I am sorry but I just don't get it
how is it possible that the error is related to that?
I just saw that static files are managed by the web server when Debug is set to False, why that? I mean all the files are in /staticfiles, why get them from the server, and maybe, perform a longer task to get them?
Has anyone seen a guide to Facebook ToS as it relates to bots that make comments. I see a lot of info about Messenger bots.but not about comments. I'm specifically interested in helping admins of a group within their own group.
Hi guys i need one help
how to check the duplicate record in all the fields like (name,email,id)
in django
how about enforcing Unique property
it will prevent creating records in database that aren't unique
@inland oak Btw i think django way of duplicating record is setting id to None and saving it? 😅
(used django) This is thr class in forms.py
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
username = forms.CharField(max_length=30)
class Meta:
model = User
fields = ['username','email']
what should I do to not update? (before this username was fixed to max 150 characters by defaut)
before I added that username variable (basically trying to chnage the max length from 150 to 30) by defualt the username with spaces (or anyhting beside letters, numbers and those characters) will not be updated but here it does.
or to be more exact I need a way to change the max length of the username without changing other stuffs that are in default
What's the problem here?
You have whitespaces in your username, they probably are not permitted by default
huh? You can forbid Blank values too
I meant that it's the way to duplicate record essentially 🤔
e.g.
item = Item.objects.get(pk=1)
item.id = None
item.save()
before I added that username variable (basically trying to chnage the max length from 150 to 30) by defualt the username with spaces (or anyhting beside letters, numbers and those characters) will not be updated but here it does.
or to be more exact I need a way to change the max length of the username without changing other stuffs that are in default
Hi
idk how to do that can please share me some resources
I made a login page and register page using MySQL and flask
GitHub link to my project : https://github.com/turbomaster95/flask-website-with-sql-database
deploy it on heroku
heroku doest support mysql i think
what
The Procfile
ohh but i use django this is how in django look like
ohh try searching on internet
basically bing
i know termux
i used it initally for phishing attacks with shellphish
I have AllHackingTools installed
ohh but i dont use attacking now
hmm
i just create scripts for attacking
using python and metasploit generate payload and embed it with my python application
and also do backend development using django
Command to install on termux :
git clone https://github.com/mishakorzik/AllHackingTools && cd AllHackingTools && chmod +x Install.sh && ./Install.sh
ohh
Can u send me ur creations ?
do you able to install aircrack-ng
And how did u embed the metasploit payload into a python app?
And how did u install metasploit?
Can u teach me how to do it?
create an app and using metasploit create an payload
you can create an payload and emmbel it with application it is avilable on youtube
i forget i watch on youtube only but all is long time back i used for hack my friends insta id
termux
Can u teach me on my private discord server?
i forget it bro
ok
how do i install npm websocket in django static/js file
I did not know it was possible, cool to know
thanks
Hello, can someone can give an example of SOAP call with the requests lib ?
hey, is a cloudflare free ssl certificate enough for a website?
or should i use Lets encrypt instead?
im using their free cdn to speed up my website loading times
let's encrypt is open source go for it
What do you mean by free CDN?
Highly likely Cloudflare is using letsencrypt too under its hood
Yeh I think let's encrypt is open source
Hey what about you big project of kubernetts how project is going ?
Nice. Deployed recently to prod level servers and finished video instruction. Already ready to be used
Short description: This website helps to set up your own VPN server for easy usage on PC or mobile.
You will have an encrypted internet connection, preventing data leaks to Internet Service Providers or other third parties.
And your internet location would be shown as the location of the VPN server.
video instruction:
https://prod-default.fra1.cdn.digitaloceanspaces.com/vultr_instruction.mp4
Writing article and going to add few more features to it
Ohh that super awesome 😍 bro
What you did in this website the whole ui and ux and backend is super cooll
I think you use wiregaurd VPN in that is that is opensource can we use VMware instead of that ?
wireguard is VPN protocol
VMware is virtualization technology / + company that went as another cloud provider I think
they aren't alternatives to each other, they are different types of technologies
Ohh
I think Cisco merkic also there
i mean, you could use wireguard at different cloud providers (as well as my application can be applied to different providers)
but I get confused with your questions
Sorry I also don't have much knowledge
But how you are creating a private VPN for personal use
i wish i could figure out how ot make my own ip piggybacker
i’m pointing at cloudflare with my A records so everything is proxied through them
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
I want to add a custom color to bootstrap, but I don't have any scss files. Do I need to download the source files?
Anyone ever set up a notification system based on dates in a databse?
In settings file i have ```STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR/ "static/css",
BASE_DIR/ "static/planets",
]```
in html html {% load static %} <link rel="stylesheet" href="{% static 'menu_page.css'%}">
and no working
I think you can lookup how to overwrite bootstrap colors or how to add them with custom css.
The docs say not to touch the source .css files if it can be helped. I guess I could make a backup in case I mess anything up.
Did you from django.contrib.staticfiles.urls import staticfiles_urlpatterns and urlpatterns += staticfiles_urlpatterns() in the urls.py
Hello. In Flask, when using the Application Factory pattern together with Blueprints, why does initializing flask-restful differ from other extensions like flask-sqlalchemy? I initialize my database in the create_app function, but the api is initialized in the blueprint itself:
api_bp = Blueprint("api", __name__)
api = Api(api_bp)
#Add resources to api
api.add_resource(HelloWorld, "/")
And then I just register the blueprint in create_app() and that's it. Trying to do it like you do with a database (db.init_app(app)) doesn't work, but doing it from the blueprint directly does work.
wait
from django.contrib import admin
from django.urls import path, include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.http import HttpResponse
from django.shortcuts import render
in urls.py
If anyone has any experience in digittal advertising? If so, please DM me.
hi i got a account creation system code from git
i want to make it my own how much should i change it for it to be cosidered my code
i have this
It works but when it resets it doesn't refresh this project, I don't know why
Why are your views in your urls.py?
idk
for some purpose?
That's... not a great answer.
You might benefit from doing a Django tutorial to learn how everything should be setup.
okey
Check out djangogirls. They have a great blog tutorial.
Can i have css in folder static/css/file.css?
Yes
okey
okey
Polak?
polak
Ah, siema.
siema
ty
ja mam pytanie bo mam w pliku css tam background
i czarny mam ustawiony
a jak zmieniam to nie odświeża mi to na stronie a mam autozapisywanie
aha to ma to znaczenie
Tak oczewiszce.
Zrob to tutorial. Odrazu po tym bedziesz mial lepszy ustawienie zeby cos zbudowac.
dobra to zmieniam zaraz to i tak poza tym po co są foldery np migrations i mój game to ma znaczenie jakieś?
dobra już ogarniam
migrations to jest automatyczny log gdzie zmiany w DB sa zasawowany. Mozna tez tam cos zmienic, ale na pocatku nic tym nie musisz robic.
okej dzięki
dzięki już wszystko śmiga 🙂
!rules 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
Hi there. I am struggling to get past a very basic error using Django.
Model class django.contrib.sessions.models.Session doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
I have tried many suggested solutions online, but am struggling to even really understand what the error means
!paste Share your code
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.pythondiscord.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.
Super!
accounts.User.groups: (fields.E304) Reverse accessor for 'accounts.User.groups' clashes with reverse accessor for 'auth.User.groups'.
i am getting this error when migrating my code in django
could anyone help?
In Django, is it possible to declare a model in one app and then use it in another app?
yes
I was checking some websites and loved their design etc but realised my css skills are nil
So any recommendations on the course on css?
can someone reccomend me a tutorial to implement remember me function in
my user login page in django
I keep getting this error when I start a new project and try to run the server
python version - 3.9.5
pip freeze
asgiref==3.5.0
Django==4.0.1
sqlparse==0.4.2
Hey @crystal quiver!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
from _sqlite3 import *
ModuleNotFoundError: No module named '_sqlite3'
import sqlite3 as lite
con = lite.connect('something.something')
db = con.cursor()
Sorry this wasn't clear
This is the end of the error that comes up
I have not written any code
This is fresh after installing the django framework
Okay. Thanks anyways
if it were me, I'd use traceback, make an exception and then call traceback.format_exc()
I've found it handy when I don't want to print('here') everywhere.
How did you install it? Are you using a virtualenv?
are passwords safe in django`? how can i ensure safety when while debugging the application i can print the password in the console if i want to does it mean that the passwords users tye can be hacked
is the api only way to connect django and react?
Basically yes
oh ok
api stands for "application programming interface", basically an interface through which different programs could interact
REST is popular choice for building web api's
can we use fastapi?
You'd need something similar to interact with your django from react app
You can, but you don't **have ** to
You can build rest api's with django too, though i like fastapi more it's harder to setup
You can but it's kind of a mess 😅
Fastapi is a framework, rest is style of your api architecture
You can use rest with fastapi
oh
Stick with whatever you're most familiar with at this moment (django / fastapi)
ok thanks
does it support gql well?
(fastapi) Not by itself but yeah
thanks, that'll be definitely i gotta look into
FastAPI framework, high performance, easy to learn, fast to code, ready for production
I tried strawberry, it's pretty good
Ariadne uses schema-first approach, i'd try that too
yes
Lately everyone has been moving into graphql. Guess that will become the new standard.
graphql isn't a new thing, rest isn't going anywhere soon 😅
Well, you can use them together but grahql isn't rest
Your api can provide multiple endpoints over http, say
/users for some rest operations
/graphql for graphql queries
Yep, but REST doesn't specify a schema format, usually that's done via OpenAPI schema that would describe all your endpoints, their inputs and outputs
@sand oracle
Many libraries are still actively developed and don't have solutions for things like authentication, permissions, validation, etc
On the other hand REST is quite mature
Plus if you migrate from REST to GraphQL you still might need or want to keep the old api
github and gitlab use graphql for some of their services
Not sure about github but i think gitlab uses graphql a lot
Also if your api is used by other developers it's often easier to use REST for them than GraphQL
Does Github pages not allow having "Share on whatsapp" links?
I want to use slug in django, but when I save slug, it adds something randomly at the end
Yo guys, what's the best database to use in django? Should I just use the default one?
Sqlite is fine for development but not production. I would say go for Postgres for SQL or MongoDB for NoSQL
Can anyone help me link web app and some python script on raspberry pi please?
Is Mongodb works with django well?
I've never tried it myself
Lets clarify, MongoDB for NoSQL Document Type DB
there are multiple times of NoSQL types databases, and each one fits its own niche / usage case
I feel like I see MongoDB used with Django a lot, but I suppose the other types would work fine too?
definitely. NoSQL Key Value type database Redis/RabbitMQ is quite often used in pair with Django
Hey ! searching for someone that knows about Google Analytics reporting API :
I'm having an issue with my responses containing several pages when i'm querying segments
The page token stays the same, and if i remove the segments without changing anything else from the report request, it works as expected
Do you know what happens ?
Thanks !
Hi, I just released some of the code I use in running cron jobs in the form of a django package.
I would really appreciate if you took a look, maybe made some contributions or share some feedback.
A GitHub star would also be great. Thanks!
django-serverless-cron is a Django app with a simpler approach running cron jobs.
This is done through exposing a HTTP endpoint to invoke the jobs that allows you to run any task without having to manage always-on infrastructure.
There is also an option to run jobs via management commands and the Django admin.
Why?
----
This is essentially a replacement/supplement for a traditional OS 'cron' or 'job scheduler' system:
- Serverless cron jobs no-longer a pain.
- Schedule jobs to run at a frequency that is less than 1 min. (crontab is limited to 1 min)
- The machine running crontab is no longer a single point of failure.
- The problem with the above systems is that they are often configured at the operating system level, which means their configuration is probably not easily 'portable' and 'debug-able' (if you are developing on Windows, the scheduler works differently from Linux or Unix). Also can not easily be integrated into a development environment.
- Manually triggered cron jobs. Eg: via the Django Admin.
- Alternative to cron services that aren't always available on free (and sometimes paid) web hosting services.
- Easier access to cron job execution logs and monitoring execution failures.
- No need to learn crontab. Think of it as a friendlier alternative to traditional cron jobs. Simple cron job creation. No need for cron syntax, no guessing on job frequency. Easy controls.
hi I have the following models in django Track, Album, Artist I have to use the ListView to search from these models but we can only assign 1 model like model = Album also how I can write get_queryset method
Good day everyone, I am a Year 1 Data Science student who recently embarked on a project on the analysis of stock data. Using Dash and Flask framework only, I made a website that displays stock data information and analysis. I would like to get feedback on the project and areas of improvement. Any valuable feedback (positive and negative) is welcomed. My webpage URL is https://stonkzfu.com/. Thank you
this is my way on replacing and rendering HTML using Flask:
from flask import Flask
def render(file, str1, str2):
with open(file, 'rt') as file:
lines = [line for line in file.readlines()]
new_lines = []
for line in lines:
if str1 in line:
line = line.replace(str1, str2)
new_lines.append(line)
else:
new_lines.append(line)
file.close()
return "".join(new_lines)
app = Flask(__name__)
@app.route('/')
def page():
file = "index.html" # or whatever the name of the HTML file you are rendering
return render(file, "{ test }", "Hello World!")
if __name__ == '__main__':
app.run('0.0.0.0')
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Python Rendering test</title>
</head>
<body>
<p>{0}</p>
</body>
</html>
ez
how do I get my api-auth/login page to return the token
https://cdn.discordapp.com/attachments/342318764227821568/938493660184592455/unknown.png
im using simplejwt
Well, that error is just saying that the endpoint you're trying to reach doesn't exist - maybe it was written incorrectly in the urls.py.
I'm sure simplejwt has a method to setting up an endpoint and accessing it.
import io
from django.http import FileResponse
from reportlab.pdfgen import canvas
def some_view(request):
buffer = io.BytesIO()
context = {'vaccineDet':VaccineCenterDetails.objects.all()}
p = canvas.Canvas(buffer)
p.setFont('Helvetica-Bold', 20)
p.drawString(100, 600, "CONGRATULATIONS, YOU ARE VACCINATED!")
# Close the PDF object cleanly, and we're done.
p.showPage()
p.save()
# FileResponse sets the Content-Disposition header so that browsers
# present the option to save the file.
buffer.seek(0)
return FileResponse(buffer, as_attachment=True, filename='Vaccination.pdf')
hii, this is in my views.py, how do I pass values from the columns of VaccineCenterDetails model into this PDF?
Hello I am learning django and i want to ask if this is the correct method or not
urlpatterns = [
path('admin/', admin.site.urls),
path(r'^about/$', views.about),
path(r'^$', views.home)
]
it is showing me 404
well path function needs a simpler syntax
https://docs.djangoproject.com/en/4.0/ref/urls/#path
Here is the documentation
can my vue/react frontend grab data from a django backend WITHOUT creating a restful api with django rest framework? I've only have only learned by creating an api, but im curious why it has to be restful, cant I just grab it from the regular django urls.py ? Need help understanding that
REST is considered good practice but not required
it seems like you are not using your context variable
so could i technically use a react app with regular django instead of using their templating language? How would you fetch the data if its not over HTTP?
I'm sorry, I thought you just wanted to make your API non-REST. I'm not sure what "regular Django" would mean or how that would work without the API
You can follow GraphQL instead of REST?
But you need some kind of API for sure.
You can grab data without following either, with something like an ajax call.
(also grpc, thrift)
I think it helps to follow a REST or GQL setup if you expect to grow in complexity.
I need help with selenium
Or if your question is simple, just ask it here
im getting an error
best practices question:
When I want to save a base URL, for example 192.168.100.50/api
And there are endpoints like /api/people, /api/houses etc
is it better to have the root include the slash at the end or should I add in the slash on every axios call myself?
tldr is:
is this preferred 192.168.100.50/api or is this preferred? 192.168.100.50/api/
when being stored as a variable to be appended to endpoints?
I know this is an incredibly lame thing to ponder about lol
how to use that? pls tell the syntax..
why not have both work? django's CommonMiddleware automatically appends the / to the end of the url so visiting /api/people and /api/people/ works the same
Hello everyone, I want to make a project website in Flask in which there is a price comparison among products . The price is compared with different e commerce websites like Amazon and flipkart ( just as an example here). For example if a person comes on my site and in the search bar he searches about Samsung mobile Model - Galaxy j7, so when he clicks on the compare button, my site would show prices of that specific product from all different e commerce website( or which I have agreed to ).
How is this possible? API ? or anything else
I hope, I am able to tell you the exact problem.
Means you want Galaxy j7 right ?
Actually you can do this my web strapping or you may get API from Amazon or fipkart
A prefer a /api/ and in axios I sent in that format but in react router in use without back slash
can you explain how to do web scrapping means just an overview,
I know beautiful soup
I made a website with many different divs but when a user scrolls to a certain div I want the title to be something else than it was in the other div! How to do that?
do you know how to use #
links
today is my birthday
pls help me with this
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Test"
if __name__ == '__main__':
app.run(debug=True)
Hi, this is app.py, in browser i ger internal server error, any ideas?
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
The most basic flask fails
You have flask installed right?
This should work 🙂
read the console log of the launched application what the error contains ;b
it should be seen if the flask is launched with Flask Dev server
flask run --host=0.0.0.0 as example
No errors in the console
Hey @inland oak!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
- Running on http://127.0.0.1:5000/
do you check... server console or browser console
Server i guess :)
i have no idea then. Not shown logs, this is strange
perhaps debug mode is not fully enabled, it looks like enabled though
It's weird coz all the YouTube tutorials are the same and I did the same thing and in PyCharm i get exactly what they do, but in browser there is server error
Spill more details
Show server console
Name your OS
Browser name and version
Browser view, browser console, browser network tab
using pycharm?
OS: Win10
IDE: PyCharm
Browser: Chrome or Edge (latest)
- Serving Flask app 'app' (lazy loading)
- Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead. - Debug mode: on
- Restarting with stat
- Debugger is active!
- Debugger PIN: 119-512-554
- Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Thats from PyCharm console
How do I find the rest?
This is from browser: Unchecked runtime.lastError: The message port closed before a response was received.
Failed to load resource: the server responded with a status of 500 (INTERNAL SERVER ERROR)
clarify the way you launch the Flask server
where do you press "Run" server button, or where you insert CLI command to launch it, and what is the command
I just run the app.py in pycharm
tried to run is from CMD: python app.py as well
same result
What is your flask version
I don't know, installed it yesterday via pip
Run 'pip freeze' to see the version
Flask==2.0.2
click==8.0.3
colorama==0.4.4
Flask==2.0.2
itsdangerous==2.0.1
Jinja2==3.0.3
MarkupSafe==2.0.1
Werkzeug==2.0.2
That simplifies stuff
I ll just write dockerfile for your server
Try to run with it
We will see if smth changed
Thank you, I was thinking of it as well
As alternative
Try for now the other way...
export FLASK_APP=hello
flask run
Export or Set
Hello name of your flask file
Run server with flask run
flask run --host=0.0.0.0
- Serving Flask app 'hello' (lazy loading)
- Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead. - Debug mode: off
Usage: flask run [OPTIONS]
Error: Could not import 'hello'.
ah ok
export FLASK_APP=app
should both flask app and index.html be in same template folder?
No
Index.html should be in folder templates
flask run --host=0.0.0.0 is safe operation?
won't it expose anything to outside my pc?
i have sensitive data n my pc
It will to your local network.
It will expose only web site
Your local network is highly likely unseen to public anyway
You don't have static IP, right?
no, IP is dynamic
It can be checked by writing ipconfig and comparing shown IP with https://httpbin.org/ip
If they match, u have static public
If not, u not, u don't have public static
Anyway, run and check already
Without 0.0.0.0 if u wish
It should not be important
I have an idea, i'll use flask server on rpi anyway so i'll run flask server on rpi and try again
afaik pycharm might somehow screw up flask server if you are not pro
rpi has less stuff that can go wrong
That is why u should run it from CMD
Preferably from venv CMD
i tried both venv and outside venv
Also there is always an option to start using virtual machines of Linux
outcome is same
I ll try to run your stuff
as long as the whole project will use RPis i'll just switch the flask dev part there, just need to setup headless mode first
I dont even know how venv works in detail
well, i have everything working smoothly. Lets try docker solution then
dockerfile
FROM python:3.11.0a4-alpine3.15
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1
ENV HOME=/app
RUN mkdir $HOME
WORKDIR $HOME
RUN apk add --update make
COPY ./requirements.txt ./
RUN pip3 install -r requirements.txt
COPY . .
EXPOSE 5000
RUN chmod 777 $HOME
CMD flask run --host=0.0.0.0
requirements.txt
Flask==2.0.2
click==8.0.3
colorama==0.4.4
Flask==2.0.2
itsdangerous==2.0.1
Jinja2==3.0.3
MarkupSafe==2.0.1
Werkzeug==2.0.2
oh literally append, nvm
does the superuser credentials change after integrating postgres with django?
what will be the new credentials?
Yes because database changes
so I need to create the superuser again, right?
How much time required to learn that docker
yes
It's one of these things where you can go deep and learn a lot for a long time, but the basics you really really need don't take long. It's well worth it if you have any need at all
If you browser the docs a bit you should be able to understand what that YAML does... It's basically just using an alpine Linux image to set up a container (a little bit like a virtual machine if you've ever used VirtualBox or whatever) and then it does some basic configuration like setting environment variables and copying files into the container
thanks
this is my models.py
def vaccineDetails(request):
context = {'vaccineDet':VaccineDetails.objects.all()}
return render(request, 'display.html', context)
pls tell me how do I access the VaccineCenterName column through VaccineDetails table
done
Hello, has anyone deployed mediapipe pose detection python code using flask for websites. I am facing a problem that the output video streaming with landmarks is lagging on the website. I am trying multi-threading, however, I am facing difficulties. Can someone share their experience on tackling such a problem. Feel free to dm
who needs a web browser when you got this? 😏
from flask import Flask
import requests as res
query = input("Enter a URL: ")
page = res.get(query).text
app = Flask(__name__)
@app.route('/')
def page():
return str(page)
if __name__ == '__main__':
app.run('0.0.0.0')
Hello everyone, I need help for a django project. I created a model called "Order", and I need to create a filter system. So I created a form method="GET" with all the filters I need. But when I choose multiple values for a field (for example called "marketplace"), it's creating my url like :
?marketplace=firstvalue&marketplace=secondvalue
In the views.py, request.GET.get('marketplace') is giving me "secondvalue" only. Is there a way, without using javascript, to get multiple values for one field ?
Or is there a better way to create a filter system ? 😄
To answer this directly - the GET object is a special dict from Django that has a getlist function (Docs here: https://docs.djangoproject.com/en/4.0/ref/request-response/#django.http.QueryDict.getlist)
More broadly have a look at https://django-filter.readthedocs.io/en/stable/ which is probably going to be a more robust solution.
Is there a site that is known to allow web scraping? I want to create a project with the use of one to put on my resume, but most of the sites ive considered using have it against their terms and conditions.
@dark night
https://www.scrapethissite.com/pages/
Here are some practice pages you can scrape.
@valid void did you find a solution
Yes ! I used this https://stackoverflow.com/a/56944413
And getlist was a good solution
I use the vagrant like things but is it necessary that we have professional knowledge of docker or only that much we required for project
Hello,
Which packages can handle authentification with social networks, and native user models correctly in DRF?
hey all, does anyone know if sites like https://app.proxiesapi.com/ are safe to use?
this site basically provides an API which you could pass requests through and they'll handle things like proxy rotation, rate limits, captchas, etc
I would only be using it to pass requests to a website's API to and nothing else
help
When drag and move a canvas map like google map, there are chunks of map segment loaded shortly after, what is this technique called? Lazy loading? Canvas chunk loading?
class BookingDetails(models.Model):
username = models.CharField(max_length=255)
aadhar = models.IntegerField()
name = models.CharField(max_length = 255)
# vaccine = models.ForeignKey(VaccineDetails, on_delete = models.CASCADE)
vaccine = models.IntegerField()
status = models.BooleanField(default = False)
date = models.DateField()
def bookingdone(request):
username = request.user.username
print(username)
aadhar = request.POST['aadhar_number']
name = request.POST['Name']
date = request.POST['date']
vaccine = request.POST['vaccineid']
info = VaccineDetails.objects.get(Vaccine_ID = vaccine)
info.availability = info.availability - 1
info.save()
BookingDetails(username = username, aadhar = aadhar, name = name, date = date, vaccine = vaccine)
contexts = BookingDetails.objects.get(username = username) # why filter doesn't work
messages.add_message(request, messages.SUCCESS,'Vaccine Booked Successfully')
return redirect(customerwelcome)
there is something wrong with BookingDetails table with username field
print(username) gives me the username, but the line contexts = BookingDetails.objects.get(username = username) gives me error
what could be wrong here, pls tell
booking_details = BookingDetails(username = username, aadhar = aadhar, name = name, date = date, vaccine = vaccine)
booking_details.save()
contexts = BookingDetails.objects.get(username = username) # why filter doesn't work
You forgot to save
Btw, querying database item u just saved is ridiculous and just additional strain on database
U a welcome
i dont want to query here
I want to query in another function
I was just checking that is it working at the time i created
Okay
Your info thing can be simplified too.
U a reading from database and then updating. U a doing two actions
While u can do just one, updating the necessary thing
Also counting in such way in not transactional queries I think Is asking for troubles
Better to rewrite to transactional
Or if to keep it simple, to change the counting into another way (like quering table of substractional records)
@agile pier boop
how can I simplify the info.availability part?
Read Django orm syntax that contains
Object.update() method
thank u, after searching I simplified my expression
VaccineDetails.objects.filter(Vaccine_ID = vaccine).update(availability = F('availability')-1)
got to learn a new thing😄
👍
Learning all the time
Anyone made dosbox run from flask?
are there any websites or documentation other than the official Django documentation to learn django?
YouTube
WoW
What's a good way to make someone an admin? Flask btw
books! 😉
def userbooking(request):
bookings = BookingDetails.objects.filter(username = request.user.username) # getting the booking database of the particular user
# info = VaccineDetails.objects.filter(Vaccine_ID = bookings.vaccine) # diff bw get and filter?
# vaccineid = info.Vaccine_ID
context = {'bookings': bookings}
print(bookings.username)
why print(bookings.username) is giving error
class BookingDetails(models.Model):
username = models.CharField(max_length=255)
aadhar = models.IntegerField()
name = models.CharField(max_length = 255)
# vaccine = models.ForeignKey(VaccineDetails, on_delete = models.CASCADE)
vaccine = models.IntegerField()
status = models.BooleanField(default = False)
date = models.DateField()
django is forcing me to give default values to every field I added after I came to edit the model second time
i added 3 categories
and gave them default values
I gave a int default value to a integerfield but it says it got a empty string
and if I didn't add any default value then it says this
and it says I gave a empty string if I give a integer to it for it's default value as u can see
pls help
if you need help you should get a help channel occupied and people will help
if its something specific that u can provide code
Hey, I just started learning Django and I'm encountering a TemplateDoesNotExist error when I try to hook up my html file, I think it's caused because I'm doing something wrong in the settings.py file. The path to my html file is templates/home.html; this is what my settings file looks like: https://pastebin.com/zF6WwQNE Any help is greatly appreciated, thank you!
i got one and i think this is also for help reg web dev
check ur urls.py
It looks like this: ```py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home),
]
My views file has a home function as well:py
def home(request):
return render(request, 'home.html')```
for example, im myself need help:
I have this folder on my desktop that is purely made of cache'd html links, and i want to build a script that scrapes them all, i'll be using BeautifulSoup, but my question is there a way to build a function that would scrape the whole folder at once, or will I need to scrape them one by one
you need to first add the template folders name in settings
did u add that?
Yes, right here py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [r'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
so if you are using django 4.0 then try this .
define tamplate path like this as django doc mentioned
I guess your watching an old version Tut of django
I'm using 4.0.2, I'm getting the same error even after adding BASE_DIR:
Figured out the issue, I didn't put my project in the INSTALLED_APPS, thank you anyways, much appreciated!
yeah I saw that in your settings I wonder why I ignore it 😆
any help someone?
Scraping one file and scraping a thousand isn't too different, but yes you need to do it "one by one". Just use a basic for loop
so theres no way to build a function that could run through the whole directory and scrape all the files together into a DF?
Yes, you can do that with a simple for loop
results = []
for filename in filelist:
page_result = scrape_my_file(filename)
results.append(page_result)
I leave it to you to write your scrape_my_file function but that's the idea
def predictions(solute, solvent):
mol = Chem.MolFromSmiles(solute)
mol = Chem.AddHs(mol)
solute = Chem.MolToSmiles(mol)
solute_graph = get_graph_from_smile(solute)
mol = Chem.MolFromSmiles(solvent)
mol = Chem.AddHs(mol)
solvent = Chem.MolToSmiles(mol)
solvent_graph = get_graph_from_smile(solvent)
delta_g, interaction_map = model([solute_graph.to(device), solvent_graph.to(device)])
return delta_g, torch.trunc(interaction_map)
@app.get('/predict')
async def predict(background_tasks: BackgroundTasks):
results = background_tasks.add_task(predictions(solute,solvent))
response["interaction_map"] = (results[1].detach().numpy()).tolist()
response["predictions"] = results[0].item()
return {'result': response}
``` I was unable to pass solute and solvent in ` results = background_tasks.add_task(predictions(solute,solvent))
` but i am getting they are not defined.
ofcurse ofcurse, thank you very much tho, it helped a lot
Can I access local/session storage variables using flask? Please ping me when you reply
how do I insert a clickable link into code
Greetings, what technology would you use for simple website (busniess-card like). Website doesn't need database. I used to went with python Flask/Djagno/FastAPI but what to choose if it doesnt need database? I do not know JS as well.
no wordpress please, too slow
and I appreciate if you could ping me while answering, thank you
I personally like Hugo a lot. Pick a template, tweak it as needed, and generate your site.
You could also just build the site directly with traditional HTML and CSS. Bootstrap is probably worth looking at if you want to do that
Signals might work for you
Wdum
Hi guys
I
I'm not too familiar with web dev and python, but I'm trying to create a login system where a large group of people can login to the website and redeem their points
Currently, I've been thinking of using Postgresql as the database, python as backend, and the frontend well whatever the front-end dev wants to use (which is not me)
For the backend, would flask suffice?
I believe it would for the most part
So I wouldn't need something like fastapi correct?
I was told that I needed an api to interact between postgresql and the front end, so in this case
would flask take care of that?
I'm not an expert on backend but I think you should try django
I was thinking about django, but I heard it has a steeper learning curve than flask, and right now, I'm trying to finish the website by june so that's why I been thinking of using flask
@normal cipher btw can u answer this question?
you can easily learn django in a month including rest framework if you already know python
there are extensions for db access.
But tbh, for the nitty gritty details of flask vs fastapi, I wouldn't be the best person
Why do you recommend django over flask? It's more powerful or something?
no, you won't need fast api if you are using django
okay so really I just need django, postgresql, front-end?
django is alot better than flask. it provides a MTV and normal security + django is better with urls and modules
This is going to be my most "complex" project up to date, so please bear with my questions lol
sure, ask me anything anytime
Okay sounds good. Do you have any recommendations to get started in django?
Also, I'll be SSH into a raspberry-pi (the server) which is going to hold the database, does that influence anything?
if you like reading, I would say read docs but you can watch Traversy media course of django
oh yeah reading is faster, thanks. Mind if I dm you if I have questions?
sure, why not
alright thanks for your help today
class VaccineCenterDetails(models.Model):
Center_Id = models.IntegerField(primary_key = True)
pin_code = models.IntegerField()
VaccineCenterName = models.CharField(max_length = 255)
address = models.CharField(max_length = 255)
def __str__(self):
return self.VaccineCenterName
class VaccineDetails(models.Model):
Vaccine_ID = models.IntegerField(primary_key = True)
Center = models.ForeignKey(VaccineCenterDetails, on_delete = models.CASCADE)
type_of_vaccine = models.CharField(max_length = 255)
availability = models.IntegerField()
def __str__(self):
return self.type_of_vaccine
How do I filter on the basis of foreign key field ?
def search(request):
pincode = request.POST['pincode']
context = {'vaccineDet':VaccineDetails.objects.filter(VaccineCenterDetails__pin_code__contains = pincode)}
return render(request, 'display.html', context)
I tried using __ but i m a little confused
Since they recommend Django
https://www.django-rest-framework.org/
Then u could probably have a look at this to add
Django, API, REST, Home
For your situation, Django augmented with DRF should be nicer
What's the purpose? Sorry I'm hella confused
Is it like an add-on to django?
It is out of the box solution to make API out of Django, prepared to serve as just backend to different front
solved
it was Center__pin_code = pincode
Yes
Okay so django is the framework for the backend, then I just use django-rest-framework as the api?
Basically it is bunch of already prepared solutions for all your problems to make Rest API
What are the different types of APIs I can use? Only Rest right?
Your sentence is not making sense to me
There are different options, REST API is the dumbest easiest one. It should be all u need
For the backend, I use the django framework right? And the whatever u just linked will act as the REST API?
I linked you Django Rest Framework, it will serve to be used as Django backend framework to make a REST API
How would I protect one of my routes?
Like if a certain role can access the route
Seeing no details, which framework or any code the person wishes to protect, darkwind gave sensible advice:
Take pepper spray for protection with you!
Anyway.. if it is Django, you need just to extract current user for the request
Check his role
And return error for all who don't match your criteria
Feel free to wrap into decorator, for reusage at other routes
Technically same thing in any other Frameworks.
Difference only in different way to acquire Auth state, which depends on which Auth system u used
Btw the comedy was appreciated
Why did he have 3 function
When I mostly see 2
Nani
how do i reply to a GET /favicon.ico HTTP/1.1GET / I tried to respond it with this
HTTP/1.1 200 OK
Content-Type: text/html
<!DOCTYPE html>
<html lang="en"><head></head>
<body><img src="htdocs/favicon.ico"></body></html>
but it doesn't seem to be working, I have the favicon.ico image in htdocs folder
i am building a webserver with socket module
Darkwind looked at the random rendered html code of an unknown code and unknown framework
And questioned:
uhm?
you have to be providing a bit more details about your situation
if you wish other people to help you
how do i respond to a http request that says GET /favicon.ico HTTP/1.1GET /
i am building a webserver from socket
not using any framework like django or flask
code examples are welcome
examples?
i just want to know the basic reply to GET /favicon.ico HTTP/1.1GET / when you have the image
okay, I guess it is clear enough now
other wise i would just respond with HTTP/1.1 404 <CRLF><CRLF>
when the user didn't has the image
but now i have the image and i want to respond with the image
view-source:https://flask.palletsprojects.com/en/2.0.x/tutorial/static/
i am checking source code view for <link rel="shortcut icon" href="../../_static/flask-icon.png"/>
it renders this code if opened in a separate page this url
https://flask.palletsprojects.com/en/2.0.x/_static/flask-icon.png
<html style="height: 100%;"><head><meta name="viewport" content="width=device-width, minimum-scale=0.1"><title>flask-icon.png (180×161)</title></head><body style="margin: 0px; background: #0e0e0e; height: 100%"><img style="-webkit-user-select: none;margin: auto;background-color: hsl(0, 0%, 90%);transition: background-color 300ms;" src="https://flask.palletsprojects.com/en/2.0.x/_static/flask-icon.png"></body></html>
i did reply the same
just didn't include the css
hmm. perhaps somehow directly file can be sent in the request
files can be attached to request
yes?
as the only idea I have...
...you could try to enable thing like Wireshark
raise dummy http server wtihout ssl
and to request from your browser the favicon.ico object
you should be able in Wireshark to sniff exactly how the answer is looking like
wait so i respond to a request with my own request?
Or perhaps favicon just can't be transmitted in the web socket protocol?
I am a bit unsure how you try to transmit it
you know socket module?
We can send an image as encoded into base64
yes i read about that how to do that
nah, never dealt with socket beyond seeing the code of a simple web chat
and coding a chat with sockets in the past 🤔
in C++
Where are you responding at all?
provide code example actually 😉
so far you look like trying to imitate web server to me
are you trying to reinvent the nginx?
client_connection, client_address = server_socket.accept()
...
client_connection.sendall(response.encode())
client_connection.close()
response is this thingy
definition of server_socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((SERVER_HOST, SERVER_PORT))
server_socket.listen(1)
👆
http://www.columbia.edu/~fdc/sample.html
lets see, if we enable this testing web site without encryption
We can see favicon sent with 200 code in type x-icon thing!
yess
how do i even send it in x-icon
i tried reading the favicon.ico with "rb" and truncated it to response
but it didnt display
Oh look, detailed about request of favicon
Content-Type image/x-icon
remember we were setting in python Content-Type application/json when sending json answers? looks the same
i was setting text/html when sending my stuff
@inland oak or else
Request Headers
GET /favicon.ico HTTP/1.1
Host: www.columbia.edu
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36
DNT: 1
Accept: image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8
Referer: http://www.columbia.edu/~fdc/sample.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9,ru;q=0.8
Cookie: BIGipServer~CUIT~www.columbia.edu-80-pool=1730689920.20480.0000
Response Headers
HTTP/1.1 200 OK
Date: Sat, 05 Feb 2022 11:37:44 GMT
Server: Apache
Last-Modified: Tue, 09 Jan 2018 21:27:53 GMT
Accept-Ranges: bytes
Content-Length: 5430
Vary: User-Agent
Keep-Alive: timeout=15, max=88
Connection: Keep-Alive
Content-Type: image/x-icon
Set-Cookie: BIGipServer~CUIT~www.columbia.edu-80-pool=1730689920.20480.0000; expires=Sat, 05-Feb-2022 17:37:44 GMT; path=/; Httponly
xD, never dealt with it before, but looks like fun
where did it send the favicon.cico i cant see it
do i need to like gzip it
because i tried that too
not sure, Content-Length: 5430 i can see only this a trace of icon for now
let me try this but adding the content of favicon.ico to this
I think you don't need gzip
it is just browser sends request, that it CAN accept in gzip
but it should NOT HAVE to be response with gzip
yea i figured it out when it didnt work
it can accept encodings like br and deflate too
Found another Clue!
bytes?
Hey @inland oak!
It looks like you tried to attach file type(s) that we do not allow (.har). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
Hey @inland oak!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
dammit
paste bin
yessss
xD, even having no idea about the thing, I found it. yay.
okay but what now?
the data i read from ico file is \x00\x011
is like that
obviously it is base64 encoded
yeah, it is even told there
encoded: base64 in the json
Just for the future debugging purposes, the json was received in Network chrome tab
when Ctrl+F5 resources and right clicking to save all as HAR at http://www.columbia.edu/~fdc/sample.html
still not working
here is what i have
with open(f"htdocs/favicon.ico", "rb") as f:
response += f"Content-Length: {len(f.read())}\n\nContent-Type: image/x-icon\n\n"
response = response.encode() + f.read()
print(response)
client_connection.sendall(response)
prints this
b'HTTP/1.1 200 OK\n\nContent-Length: 1150\n\nContent-Type: image/x-icon\n\n'
what's a jk
yes
https://stackoverflow.com/questions/47294234/dont-know-how-to-transfer-files-over-python-socket-server
not working but possible a hint for clues
he sends favicon too
woah still unanswered
probably because the title is bad
need to be named respond to Get request for favicon using local web server via sockets
or something like that
this was given from professor
so it should be in theory half working already
just few things to fix
hmm he re-econded it to utf-8
the favicon file
the https://www.rfc-editor.org/rfc/rfc1341#page-51 it says too less
highly likely it is python2
i kinda did literally the same
elif data[0:25] == "GET /favicon.ico HTTP/1.1":
print "favicon"
contents = open("favicon.png", "rb").read()
socko.send("HTTP/1.1 200 OK\r\n"
"Connection: close\r\n" +
"Content-Type: image/png\r\n" +
"Content-Length: " + str(len(contents)) + "\r\n\r\n" +
contents)
except i dont know about the \r
it is png?
i have the file as favicon.ico

yea ik
it can also be sent in jpg
shall i try using a png?
but the colombian site sent a ico
i literally hate rfc it is so hard to navigate
let me try adding \r
Text files created on DOS/Windows machines have different line endings than files created on Unix/Linux. DOS uses carriage return and line feed ("\r\n") as a line ending, which Unix uses just line feed ("\n").
i think it is just a windows thing
ah i am not windows
so the only thing that differes is the png
and the encoding
with open(f"htdocs/favicon.icon", "rb") as f:
response += f"Content-Length: {len(f.read())}\r\nContent-Type: image/x-icon\r\n\r\n"
response += f.read()
client_connection.sendall(response.endcode())
as expected it throws a error when not encoding the response
before __iadd__ to f.read()
hey guys, anyone willing to help regarding objects.annotation in class based view?
@inland oak progress
with open(f"htdocs/{filename}", "rb") as f:
data = f.read()
response += f"Content-Length: {len(data)}\nContent-Type: image/x-icon\n\n"
response = response.encode() + data
print(response)
spats out this
Hey @wraith pond!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
well, duh
duh?
data = f.read() is a byte array
response += f"Content-Length: {len(data)}\nContent-Type: image/x-icon\n\n"
response = response.encode() + data
you add byte info to regular text info
i see you encoded response.encode()