#web-development

2 messages · Page 214 of 1

native tide
#

django will be helpful in situation like this if you want for be able to save before downloads of user to databse

#

for my opinion, nothing comes close to django admin interface. if u understand u see the beauty in easiness it makes :)

golden bone
#

I don't know what get_engine() is but it's expecting an argument

crimson monolith
#

Thanks! I'll check that link

feral night
golden bone
golden bone
jaunty berry
#

hello sir, can i ask somequestion about django4 in here ?

chilly quest
#

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?

swift wren
#

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

echo flicker
#

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?

normal cipher
echo flicker
#

I do want to experiment with django...

normal cipher
echo flicker
#

Can you suggest some resources to learn and implement django?

normal cipher
# echo flicker 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...

▶ Play video
echo flicker
#

👍

#

What about Dennis Ivy?

normal cipher
#

Dennis Ivy is great and there is another channel you might want to check out, it's Just Django

digital thorn
#

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

lavish prismBOT
#

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.

fallow crown
#

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?

patent sandal
#

if web based app maybe angular and react with node.js

wheat verge
#

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.

normal cipher
normal cipher
wheat verge
#

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

normal cipher
#

can you show me your base.html and home.html

wraith pond
#

does fetch api work in brave?

golden bone
versed epoch
#

Hell.
I am Django developer.
I want to find some jobs here.

native tide
#

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

river arrow
#

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>

latent cosmos
#

FastAPI or Flask/Django, what to choose for web dev?

#

ping me with answers pls

hazy hedge
latent cosmos
#

thank you

#

what is rpc

#

@hazy hedge

hazy hedge
next musk
#

Any good source to learn React Js for beginners ??

hazy hedge
wooden river
#

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?

silent hatch
#

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()
honest dock
#

can you show the error? and where exactly it's crashing?

silent hatch
#

the error is:
AttributeError: 'NavigableString' object has no attribute 'contents'

golden bone
river arrow
golden bone
river arrow
golden bone
river arrow
# golden bone 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

golden bone
river arrow
#

l = browser.find_element_by_class_name("textarea")
l.send_keys("Selenium")
#send keyboard input
l.send_keys(Keys.RETURN)

compact vapor
honest dock
tired kraken
#

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?

golden bone
tired kraken
#

Damn for skipped again

quaint maple
#

Hi! How can i replace this "Password (again)" for "Repeat your password" in django allauth??

warped aurora
#

how do i get jinja to recognize that variable

warped aurora
#

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>'

jovial cloud
drifting radish
#

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()```
river arrow
golden bone
zealous tundra
#

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

native tide
#

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.

eternal blade
#

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

vague ember
#

That could become quite complex depending on the scale of the system

digital thorn
#

i need help can some one help me with this

vague ember
#

because the error complains it doesn't exist

digital thorn
#

yes i know but when i migrate it not creating tab;e

#

this the table

stoic lark
#

sqlite3 is better or mysql mongodb better for django ?

elfin kraken
#
<!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

elfin kraken
#

I corrected that now but its still not appearing on my browser

potent tendon
#

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

potent tendon
potent tendon
normal cipher
# digital thorn this the table

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

sturdy jungle
#

Anybody knows what this selected effect is known as ?

sturdy jungle
silent hatch
slim skiff
silent hatch
#

ah fk sec i'll update that

slim skiff
#

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

silent hatch
#

so like...

for offset in range(0,60000):
    .
    .
    .

im kinda confused with what to do inside

#

or would it be, offset+50

slim skiff
#

give me a second, I'll get to my pc and be more helpful 😀

silent hatch
#

lol sure

slim skiff
#

@silent hatch

#

claim one of the help channels by posting in it

silent hatch
#

claimed avocado

warm mesa
#

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

native tide
#

Are there other services like Heroku where I can easily deploy a Flask app?

golden bone
# stoic lark sqlite3 is better or mysql mongodb better for django ?

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

golden bone
native tide
#

@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.

golden bone
eternal blade
#

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
knotty robin
#

Hey can someone tell me why this happens?

agile pier
mint flame
#

Does anyone here know how to use the django frame work

golden bone
golden bone
golden bone
# knotty robin

What does the "Learn More" link say? And how recently did you change those DNS records?

rose fulcrum
#

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

honest dock
#

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?

mint flame
honest dock
rose fulcrum
tired kraken
#

@honest dock Familiar with AnonymousUser permissions? Which api are u using? Rest or GraphQL?

gentle ingot
#

Can someone here help me with bs4?

cyan cobalt
#

@gentle ingot glad to help

gentle ingot
#

Im making a crawler .Not sure how closely that is related to this channel lol

cyan cobalt
#

or you can ask a question about BeautifulSoup4

gentle ingot
#

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.

cyan cobalt
#

@gentle ingot That is the whole purpose for a channel. So they can give you further information about the situation.

gentle ingot
#

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.

cyan cobalt
#

Not going to lie, I have no knowledge about bs4; so I can't help you.

#

@gentle ingot Maybe you can ask someone else

gentle ingot
#

Thats okay. thanks for the channel suggestions. heading there

cyan cobalt
#

@gentle ingot Glad to help

vague ember
# eternal blade oh thanks, how can I implement the push approach using django channels?

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
lavish prismBOT
#

: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).

wheat verge
#
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?

drifting radish
golden bone
# drifting radish

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?

drifting radish
#

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()```

golden bone
drifting radish
#

hah working

#

but

#

i have question

#

what is migrations folder

#

What is he for

golden bone
# drifting radish What is he 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

drifting radish
#

ok

#

ey

modest hazel
#

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

modest hazel
#

nvm me, was just a version issue

vivid canopy
#

What kind of work do python backed junior Django

warm dagger
#

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 %}
golden bone
warm dagger
#
word-break: break-all;
#

this worked. and why tf I didn't try this before :(

#

though thanks

#

👍

eternal blade
vague ember
inland oak
#

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.

inland oak
graceful igloo
#

Congratulations my dude

inland oak
#

I was architect
I was backend Dev
I was infrastructure Dev
I was Frontend Dev

graceful igloo
#

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

twilit needle
#

It looks very nice @inland oak does it use python for the backend? I mean it's kinda obvious tho lol

twilit needle
#

What are you using on the frontend?

#

Is it django rendering templates or something like react?

scenic willow
inland oak
silent hatch
#

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

exotic jay
#

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

inland oak
exotic jay
dense slate
#

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.

light cloak
#

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?

silent hatch
#

maybe someone could help me around, how can I concatenate the data I parsed using scraping functions into a DF?

sacred crane
#

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?.

dense slate
#

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.

sacred crane
#

Did you mean using JWT?

dense slate
sacred crane
#

Thanks

silent hatch
drifting radish
#

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>```
native tide
#

looks like skill issue tbh.

modest hazel
#

kidding,

"""

```py
"""
#

well, that's tough to show

#

put the code in between the three backticks

zinc lagoon
south arch
#

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?

dense slate
#

I wonder if you have a cached version showing.

south arch
#

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

dense slate
#

You sure you edited the correct file?

south arch
#

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

dense slate
#

What's it showing incorrectly? The CSS or the template itself?

south arch
#

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

dense slate
#

are your dirs correct? shouldn't there be / at the end?

south arch
#

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?

silent hatch
#

nothing happend3s without a reason

dense slate
#

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.

south arch
#

I think that there's a problem with myself then

#

when I do
{% load static %}
and use
{% static 'website/stuff.css' %}

south arch
#

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

dense slate
#

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.

south arch
#

yeah but I did check that the files are correct

#

I do have an idea

south arch
#

it could give me some informations

dense slate
#

ah ok

south arch
#

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?

golden bone
#

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.

digital thorn
#

Hi guys i need one help
how to check the duplicate record in all the fields like (name,email,id)
in django

inland oak
#

it will prevent creating records in database that aren't unique

serene prawn
#

@inland oak Btw i think django way of duplicating record is setting id to None and saving it? 😅

warm dagger
#

(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

serene prawn
#

You have whitespaces in your username, they probably are not permitted by default

inland oak
serene prawn
#

e.g.

item = Item.objects.get(pk=1)
item.id = None
item.save()
warm dagger
# serene prawn What's the problem here?

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

merry karma
#

Hi

digital thorn
merry karma
#

I made a login page and register page using MySQL and flask

merry karma
#

I tried

#

But my procfile doesn't like me

digital thorn
#

heroku doest support mysql i think

digital thorn
merry karma
#

The Procfile

digital thorn
merry karma
#

I use flask

#

I made it in termux

digital thorn
digital thorn
merry karma
#

One min

#

Look at this

#

Linux in Android from playstore

merry karma
digital thorn
# merry karma

i used it initally for phishing attacks with shellphish

merry karma
digital thorn
digital thorn
#

using python and metasploit generate payload and embed it with my python application

#

and also do backend development using django

merry karma
digital thorn
#

do you able to install aircrack-ng

digital thorn
merry karma
#

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?

digital thorn
# merry karma And how did u install metasploit?

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

digital thorn
merry karma
#

Can u teach me on my private discord server?

digital thorn
merry karma
#

DM me

#

I will send the link

digital thorn
pallid lily
#

how do i install npm websocket in django static/js file

inland oak
#

I did not know it was possible, cool to know

pallid lily
#

thanks

grizzled crescent
#

Hello, can someone can give an example of SOAP call with the requests lib ?

main prairie
#

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

stark tartan
stark tartan
inland oak
stark tartan
stark tartan
inland oak
# stark tartan 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

https://shapevpn.com/

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

stark tartan
#

What you did in this website the whole ui and ux and backend is super cooll

stark tartan
inland oak
#

they aren't alternatives to each other, they are different types of technologies

stark tartan
#

I think Cisco merkic also there

inland oak
#

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

stark tartan
#

But how you are creating a private VPN for personal use

swift wren
#

i wish i could figure out how ot make my own ip piggybacker

main prairie
inland oak
#

!rule 5

lavish prismBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

pure nimbus
#

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?

warped aurora
#

Anyone ever set up a notification system based on dates in a databse?

drifting radish
#

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

dense slate
pure nimbus
#

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.

mental summit
crimson monolith
#

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.

drifting radish
#

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

shrewd warren
#

If anyone has any experience in digittal advertising? If so, please DM me.

zinc lagoon
#

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

drifting radish
#

It works but when it resets it doesn't refresh this project, I don't know why

dense slate
drifting radish
drifting radish
dense slate
#

That's... not a great answer.

#

You might benefit from doing a Django tutorial to learn how everything should be setup.

drifting radish
#

okey

dense slate
#

Check out djangogirls. They have a great blog tutorial.

drifting radish
dense slate
#

Yes

drifting radish
dense slate
#

Polak?

drifting radish
#

polak

dense slate
#

Ah, siema.

drifting radish
#

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

dense slate
#

Rozumiem, ale masz views w urls.py, i to nie bedzie dzialalo.

drifting radish
#

aha to ma to znaczenie

dense slate
#

Tak oczewiszce.

#

Zrob to tutorial. Odrazu po tym bedziesz mial lepszy ustawienie zeby cos zbudowac.

drifting radish
#

dobra to zmieniam zaraz to i tak poza tym po co są foldery np migrations i mój game to ma znaczenie jakieś?

dense slate
#

migrations to jest automatyczny log gdzie zmiany w DB sa zasawowany. Mozna tez tam cos zmienic, ale na pocatku nic tym nie musisz robic.

drifting radish
#

okej dzięki

drifting radish
golden bone
#

!rules 4

lavish prismBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

vital olive
#

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

lavish prismBOT
#

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.

dense slate
zinc lagoon
#

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?

fickle saddle
#

In Django, is it possible to declare a model in one app and then use it in another app?

burnt cedar
#

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?

zinc lagoon
#

can someone reccomend me a tutorial to implement remember me function in
my user login page in django

crystal quiver
#

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

lavish prismBOT
#

Hey @crystal quiver!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

crystal quiver
#

from _sqlite3 import *
ModuleNotFoundError: No module named '_sqlite3'

native tide
crystal quiver
#

This is the end of the error that comes up

#

I have not written any code

#

This is fresh after installing the django framework

native tide
#

error from pip?

#

Oh.

#

Not sure then. I'm more a flask person than django.

crystal quiver
#

Okay. Thanks anyways

native tide
#

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.

wintry hearth
zinc lagoon
#

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

thin dome
#

is the api only way to connect django and react?

serene prawn
thin dome
#

oh ok

serene prawn
#

api stands for "application programming interface", basically an interface through which different programs could interact

#

REST is popular choice for building web api's

thin dome
#

can we use fastapi?

serene prawn
#

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

thin dome
#

wait

#

we can setup fastapi in django?

serene prawn
#

You can but it's kind of a mess 😅

thin dome
#

which ones easier rest or fastapi?

#

i think fastapi

serene prawn
#

Fastapi is a framework, rest is style of your api architecture

#

You can use rest with fastapi

thin dome
#

oh

serene prawn
#

Stick with whatever you're most familiar with at this moment (django / fastapi)

thin dome
#

ok thanks

wooden ruin
serene prawn
wooden ruin
#

thanks, that'll be definitely i gotta look into

serene prawn
#

I tried strawberry, it's pretty good

#

Ariadne uses schema-first approach, i'd try that too

pure forum
serene prawn
#

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

native tide
#

Does Github pages not allow having "Share on whatsapp" links?

waxen harbor
#

I want to use slug in django, but when I save slug, it adds something randomly at the end

fickle saddle
#

Yo guys, what's the best database to use in django? Should I just use the default one?

golden bone
hard whale
#

Can anyone help me link web app and some python script on raspberry pi please?

stark tartan
golden bone
#

I've never tried it myself

inland oak
#

there are multiple times of NoSQL types databases, and each one fits its own niche / usage case

golden bone
#

I feel like I see MongoDB used with Django a lot, but I suppose the other types would work fine too?

inland oak
inland oak
eternal mulch
real blade
#

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 !

opaque flax
#

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!

https://github.com/paulonteri/django-serverless-cron

GitHub

django-serverless-cron 🦡 A Django app with a simpler approach running cron jobs (mostly in a serverless environment) through HTTP requests with an integration with the Django admin. This allows you...

#

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.

https://github.com/paulonteri/django-serverless-cron

GitHub

django-serverless-cron 🦡 A Django app with a simpler approach running cron jobs (mostly in a serverless environment) through HTTP requests with an integration with the Django admin. This allows you...

regal fossil
#

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

unkempt cloak
#

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

wheat fern
#

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

narrow bison
#

im using simplejwt

dense slate
#

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.

agile pier
#
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?

weary gull
#

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

finite root
jaunty magnet
#

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

golden bone
finite root
jaunty magnet
golden bone
dense slate
#

But you need some kind of API for sure.

#

You can grab data without following either, with something like an ajax call.

vague ember
#

(also grpc, thrift)

dense slate
#

I think it helps to follow a REST or GQL setup if you expect to grow in complexity.

buoyant star
#

I need help with selenium

golden bone
buoyant star
#

im getting an error

visual cedar
#

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

agile pier
wooden ruin
ocean slate
#

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.

stark tartan
stark tartan
stark tartan
ocean slate
#

I know beautiful soup

wet meadow
#

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?

native tide
#

links

wet meadow
#

I want the title to change not the url

native tide
#

today is my birthday

hard whale
#
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

thin marten
#

You have flask installed right?

inland oak
#

it should be seen if the flask is launched with Flask Dev server

#

flask run --host=0.0.0.0 as example

lavish prismBOT
#

Hey @inland oak!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

hard whale
inland oak
hard whale
#

Server i guess :)

inland oak
#

i have no idea then. Not shown logs, this is strange

#

perhaps debug mode is not fully enabled, it looks like enabled though

hard whale
#

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

inland oak
hard whale
#

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)

inland oak
#

where do you press "Run" server button, or where you insert CLI command to launch it, and what is the command

hard whale
#

I just run the app.py in pycharm

#

tried to run is from CMD: python app.py as well

#

same result

inland oak
hard whale
#

I don't know, installed it yesterday via pip

inland oak
hard whale
#

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

inland oak
#

Or docker desktop

hard whale
#

both

#

not 100% sure if installed them correctly

#

but yes i installed them

inland oak
#

That simplifies stuff

#

I ll just write dockerfile for your server

#

Try to run with it

#

We will see if smth changed

hard whale
#

Thank you, I was thinking of it as well

inland oak
#

As alternative

inland oak
inland oak
#

Hello name of your flask file

#

Run server with flask run

#

flask run --host=0.0.0.0

hard whale
#
  • 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

inland oak
#

export FLASK_APP=app

hard whale
#

should both flask app and index.html be in same template folder?

inland oak
#

Index.html should be in folder templates

hard whale
#

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

inland oak
#

You don't have static IP, right?

hard whale
#

no, IP is dynamic

inland oak
#

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

hard whale
#

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

inland oak
hard whale
#

i tried both venv and outside venv

inland oak
#

Also there is always an option to start using virtual machines of Linux

hard whale
#

outcome is same

inland oak
hard whale
#

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

inland oak
inland oak
# hard whale I dont even know how venv works in detail

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
silent hatch
#

oh literally append, nvm

agile pier
#

does the superuser credentials change after integrating postgres with django?
what will be the new credentials?

agile pier
#

so I need to create the superuser again, right?

stark tartan
golden bone
#

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

agile pier
#

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

agile pier
#

done

frank shoal
#

You would need to create a relationship

fickle basin
#

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

wheat fern
#

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')
valid void
#

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 ? 😄

lilac solar
dark night
#

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.

tough sparrow
#

@valid void did you find a solution

valid void
#

And getlist was a good solution

stark tartan
cerulean dock
#

Hello,

Which packages can handle authentification with social networks, and native user models correctly in DRF?

shy canopy
#

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

native tide
warm dagger
#

u must have made some error.

autumn birch
#

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?

agile pier
#
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

agile pier
inland oak
# agile pier 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

agile pier
#

oo yes

#

thank u, how silly🙄

inland oak
#

U a welcome

agile pier
#

I want to query in another function
I was just checking that is it working at the time i created

inland oak
#

Okay

inland oak
#

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

agile pier
inland oak
agile pier
#

VaccineDetails.objects.filter(Vaccine_ID = vaccine).update(availability = F('availability')-1)

#

got to learn a new thing😄

inland oak
digital hinge
#

Anyone made dosbox run from flask?

wheat verge
#

are there any websites or documentation other than the official Django documentation to learn django?

digital hinge
#

YouTube

wheat verge
#

WoW

glacial portal
#

What's a good way to make someone an admin? Flask btw

south arch
#

what can I do?

native tide
#

Need to have a callback from a web server after authentication

#

how do i do that?

agile pier
#
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()
sand stirrup
#

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

silent hatch
#

if its something specific that u can provide code

livid pike
#

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!

agile pier
livid pike
#

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')```

silent hatch
#

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

valid vale
#

did u add that?

livid pike
#

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', ], }, }, ]

valid vale
#
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

livid pike
#

Figured out the issue, I didn't put my project in the INSTALLED_APPS, thank you anyways, much appreciated!

valid vale
#

yeah I saw that in your settings I wonder why I ignore it 😆

golden bone
silent hatch
golden bone
#
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

sacred crane
#
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.
silent hatch
snow edge
#

Can I access local/session storage variables using flask? Please ping me when you reply

unkempt wave
#

how do I insert a clickable link into code

latent cosmos
#

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

golden bone
dense slate
native tide
native tide
#

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?

vague ember
native tide
#

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?

normal cipher
native tide
native tide
normal cipher
vague ember
native tide
normal cipher
native tide
normal cipher
native tide
#

This is going to be my most "complex" project up to date, so please bear with my questions lol

normal cipher
native tide
#

Also, I'll be SSH into a raspberry-pi (the server) which is going to hold the database, does that influence anything?

normal cipher
native tide
native tide
agile pier
#
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

inland oak
#

For your situation, Django augmented with DRF should be nicer

native tide
#

Is it like an add-on to django?

inland oak
agile pier
inland oak
native tide
# inland oak Yes

Okay so django is the framework for the backend, then I just use django-rest-framework as the api?

inland oak
native tide
inland oak
inland oak
native tide
inland oak
glacial portal
#

How would I protect one of my routes?

#

Like if a certain role can access the route

inland oak
#

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

glacial portal
#

I see thanks!

#

I would have to learn decorators tho

glacial portal
glacial portal
#

Why did he have 3 function

#

When I mostly see 2

glacial portal
#

Nani

wraith pond
#

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

inland oak
#

And questioned:

inland oak
#

if you wish other people to help you

wraith pond
#

i am building a webserver from socket

#

not using any framework like django or flask

inland oak
#

code examples are welcome

wraith pond
#

examples?

#

i just want to know the basic reply to GET /favicon.ico HTTP/1.1GET / when you have the image

inland oak
#

okay, I guess it is clear enough now

wraith pond
#

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

inland oak
#

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>
wraith pond
#

just didn't include the css

inland oak
#

hmm. perhaps somehow directly file can be sent in the request

#

files can be attached to request

wraith pond
#

yes?

inland oak
#

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

wraith pond
#

wait so i respond to a request with my own request?

inland oak
#

Or perhaps favicon just can't be transmitted in the web socket protocol?
I am a bit unsure how you try to transmit it

wraith pond
#

you know socket module?

inland oak
#

We can send an image as encoded into base64

wraith pond
#

yes i read about that how to do that

inland oak
#

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++

wraith pond
#

nice

#

story

inland oak
#

provide code example actually 😉

#

so far you look like trying to imitate web server to me

#

are you trying to reinvent the nginx?

wraith pond
#
client_connection, client_address = server_socket.accept()
...
      client_connection.sendall(response.encode())
client_connection.close()
wraith pond
wraith pond
inland oak
#

We can see favicon sent with 200 code in type x-icon thing!

wraith pond
#

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

inland oak
#

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

wraith pond
inland oak
#

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
inland oak
wraith pond
#

do i need to like gzip it

#

because i tried that too

inland oak
wraith pond
#

let me try this but adding the content of favicon.ico to this

inland oak
#

it is just browser sends request, that it CAN accept in gzip

#

but it should NOT HAVE to be response with gzip

wraith pond
#

it can accept encodings like br and deflate too

inland oak
wraith pond
#

bytes?

lavish prismBOT
#

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.

inland oak
#

dammit

wraith pond
#

paste bin

inland oak
#

Check detailed info about response

#

"text" field has the data of the icon

wraith pond
#

yessss

inland oak
#

xD, even having no idea about the thing, I found it. yay.

wraith pond
#

the data i read from ico file is \x00\x011

#

is like that

inland oak
#

yeah, it is even told there

#

encoded: base64 in the json

wraith pond
#

ok now the problem

#

is

#

nvm wait

inland oak
wraith pond
#

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)
inland oak
#

is that what you are using?

#

which python version?

wraith pond
#

prints this

b'HTTP/1.1 200 OK\n\nContent-Length: 1150\n\nContent-Type: image/x-icon\n\n'
wraith pond
#

jk 2.7

inland oak
wraith pond
#

it means just kidding

inland oak
#

he sends favicon too

wraith pond
#

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

inland oak
#

so it should be in theory half working already

#

just few things to fix

wraith pond
#

hmm he re-econded it to utf-8

#

the favicon file

wraith pond
#

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

wraith pond
#

i have the file as favicon.ico

inland oak
#

favicon can be sent as png

#

I encountered such examples

wraith pond
#

yea ik

#

it can also be sent in jpg

#

shall i try using a png?

#

but the colombian site sent a ico

wraith pond
inland oak
# wraith pond 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

wraith pond
#

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()

unique nova
#

hey guys, anyone willing to help regarding objects.annotation in class based view?

wraith pond
#

@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

lavish prismBOT
#

Hey @wraith pond!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

wraith pond
#

but seriously it is still not working

wraith pond
inland oak
#

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

wraith pond
#

no

#

you see i encode

#

it before adding

inland oak
#

i see you encoded response.encode()