#web-development

2 messages · Page 206 of 1

inland oak
#

perhaps u will find some complimentary technologies to microservice them to it though

vocal prism
#

not rlly, firebase has an API

#

and an admin-sdk so you can easily use the database from python without much hassle

inland oak
#

So u a raising database through it

#

Well, let's assume it is similar to usage of managed databases then

dense slate
#

That's definitely not a good idea and I think specifically advised against. 😄

#

Although you can fake one to get back up to speed in your migrations after DB changes.

daring isle
#

I was transferring a paper reporting system to a web portal for work

inland oak
dense slate
#

I think Prisma is the favorite for JS based stuff anyhow.

inland oak
#

My JS starts and ends at frontend

#

There are other things wished being learned

#

Curious to know perhaps though

#

Considering widespread usage of js...

#

Who knows, perhaps I ll need to join developing js backend one day in a future

dense slate
#

I just think it helps knowing how it works at a global level more than being proficient with it - backend-wise.

inland oak
#

I am eyeing golang to try in a future when my learning queue would be free

#

It has some quirks though

#

After python, js, it is quite uncomfortable

dense slate
#

I thought one of the good things about Go is it's ease of use like Python

inland oak
#

Static compiled and ultra strict in best practices

#

It enforces its own vision to how code should be

inland oak
proper trench
#

Go has been popular because of goroutines

calm plume
#

That doesn't have anything to do with its philosphy

#

Go has been known to make many unpopular decisions

daring isle
native tide
#

I want to add a feature to a web app that will allow them to click and drag on an image and when they do, a box is added around the click and drag area

#

how would I implement this in javascript

orchid olive
#

ok, lets say that i am using windows 10 and is an internal server, lets forguet the https server only http

frank shoal
#

You'd probably have to do it all manually using a canvas.

#

(drawing box)

#

which means you'd have to add a setInterval(render, 1) for drawing frames.

#

or something.

#

I'm sure there's a library that does it too

orchid olive
#

help with flask and iframe
i have to show a pdf file in a iframe (if there is an other option please let me know)

<iframe src = "static/Report.pdf" class = "embeded-responsive-item" allowfullscreen></iframe>

it display the pdf windows but very very small, how can i set the width to make the view bigger?

width="750" height="500" do not works

thanks for the advice

frank shoal
#

how big is the parent div?

orchid olive
#

if that question is for me then the parent div is using whide screen and autoadjust when resize

frank shoal
#

Tried changing the size using the inspector?

#

oh, I see. You need to specify a unit. i.e. 750px

orchid olive
#

750px, also do not work with that

frank shoal
#

¯_(ツ)_/¯

orchid olive
#

ok, with the inspector: the iframe have only the src, do not shows the class also the allowfullscreen

#

<iframe src="Report.pdf">document</iframe>

frank shoal
#

What source did you put?

orchid olive
#

haaaa!! css could fix the problem

#

i think i had foud the problem, ill fix it

#

thanks any way

native tide
#

Accessibility question

#

How can I hide a parent element from screen readers?

dim rover
native tide
#

I was considering aria-hidden=true

dim rover
#

that might be more intended for things that are toggleable

native tide
dim rover
#

it says this :

The presentation role is used to remove semantic meaning from an element and any of its related child elements.

#

I would have thought so anyway

native tide
#

accessibility is hard 😦

orchid olive
#

question:

in flask, i have a form with 3 buttons, how do i tell to the webpage to "activate" the button Ok in case i hit enter instead click Ok?

native tide
haughty isle
#

Ah that's wrong

#

You want a <button type="submit"

native tide
haughty isle
#

Oh I assumed activate meant the same as click

native tide
#

My assumption could we wrong as well, communication is hard 🙂

orchid olive
native tide
#

correct this code plz
folder
|-templates
|-static
|-img
|-bg.jpg
main.py

#

<header class="masthead" style="background-image: url('{{ url_for('static', filename='img/home-bg.jpg') }} ')">

silver nexus
#

Hello, I am using flask and I am running some code but it showing my old flask code when I deleted that code. But it shows the same web page

native tide
runic bronze
#

Hi everyone, This is a Django question. it seems like a small problem but not getting how to resolve it

so this is my main url file for including app

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'',  include('home.urls')),  # home page index

This is my home url file

from django.urls import re_path as url

from . import views

urlpatterns = [
   url(r'^index/', views.index, name='index'),

This only works if i put
index/ in the pattern otherwise it dont
and the working url is
http://localhost:8000/index/
How can i make my url open same if i do
http://localhost:8000/

inland oak
#

or to make regex that matches empty and index at the same time

runic bronze
#

ahan, nice i didn't thought about it

#

let me try

inland oak
#

it should give at least warning though

#

not really best way to do that perhaps

runic bronze
#

For some reasons it works for home page but my other urls stops working

#

it would always redirect me to the home page

#

regardless of any valid url i put

#

it didn't give me any warning either

inland oak
#

I am doing it as
core/urls.py

urlpatterns = [
    path("admin/", admin.site.urls),
    path("worker", include("worker.urls")),
    path("", include("home.urls")),
]

workers/urls.py

from . import views
from django.urls import path

urlpatterns = [
    # ex: /polls/5/
    path("/ping", views.get_ping, name="ping"),
    path("/install", views.install_vpn_server, name="install"),
    path("/status", views.get_status, name="get_status"),
    path("/configs", views.get_configs, name="get_configs"),
    path("/stdout", views.get_stdout, name="get_stdout"),
]

home/urls.py

from . import views
from django.urls import path

urlpatterns = [
    # ex: /polls/5/
    path("", views.get_home, name="get_home"),
]
#

works fine

runic bronze
inland oak
#

uh, I don't need index page, it is rest API
but it would be easy to change in my case

runic bronze
#

that's the case, you aren't using regular expressions either

inland oak
#

yeah

#

all my parameters go in Query Parameters and POST Data fields

#

I don't really need any complex url patterns

runic bronze
#

i hate the fact that i can't comprehend what could be the wrong here

#

empty string should have been enough

#

and if i don't put index/

#

it starts giving me /%2F

#

extra slash on its own

#

Lol, this worked

   url(r'^/^', views.index, name='index'),
   url(r'', views.index, name='index'),
   url(r'^index/', views.index, name='index'),
#

and i have no idea why would i have do it like this

#

@inland oak

runic bronze
#

i actually amended i dont need index in the url at all

  url(r'^/^', views.index, name='index'),
  url(r'', views.index, name='index'),
#

Thanks for the chat mate

#

it looks like my mind works better if i have someone with me to talk about ti xD

inland oak
#

how about try deleting one of them

inland oak
# runic bronze it looks like my mind works better if i have someone with me to talk about ti xD

In software engineering, rubber duck debugging is a method of debugging code by articulating a problem in spoken or written natural language. The name is a reference to a story in the book The Pragmatic Programmer in which a programmer would carry around a rubber duck and debug their code by forcing themselves to explain it, line-by-line, to the...

runic bronze
runic bronze
inland oak
runic bronze
#

Hmm, that's a good idea and i think someon would have done it already

pallid lily
#

can some one give me a django verbos name and why is it used

runic bronze
#

@inland oak

   url(r'^$', views.index, name='index'),

This worked even better

#

xD

#

was that worth searching and trying for 2 hours?

dusk portal
#

Guys I need ur help

haughty isle
dusk portal
#

can u guide me asap

#

i have some more clients xD

haughty isle
#

Oh maybe get a refund then?

dusk portal
#

can u join a vc and guide me

haughty isle
runic bronze
#

Hi, you should get pythonanywhere server or Linode to host your python django app @dusk portal

#

can VC if you want

dusk portal
thorn igloo
#

i mean, a vps is a vps

dense slate
#

It's just the best, simplest tutorial I've found.

viscid walrus
#

as a beginner which language should i learn for backend web development ? any personal suggestions ?

dense slate
#

Python is a great start. Easy to understand and get the basics of programming in general.

wild cairn
#

Hey! I've made a line following robot with python on a raspberry pi and I'm wondering how could I allow someone to call the robot on a webpage so it starts that code? Would flask allow me to do that?

thorn igloo
wild cairn
thorn igloo
golden bone
manic crane
#

can someone help with this error please => AttributeError: 'tuple' object has no attribute 'values'

manic frost
#

!e

x = (1, 2, 3)
print(x.values)
lavish prismBOT
#

@manic frost :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | AttributeError: 'tuple' object has no attribute 'values'
manic crane
# manic crane can someone help with this error please => AttributeError: 'tuple' object has no...

the code => class OccupierSerializer(serializers.ModelSerializer):
token = serializers.SerializerMethodField()

email = serializers.EmailField(
    required=True,
    validators = [UniqueValidator(queryset=Occupier.objects.all())]
)

username = serializers.CharField(
    required=True,
    max_length=30,
    validators = [UniqueValidator(queryset=Occupier.objects.all())]
)

occupation = serializers.CharField(
    required=True,
    max_length = 30,
)

password = serializers.CharField(
    required=True,
    min_length=8,
    write_only = True
)

class Meta:
    model = Occupier
fields = (
    'token',
    'username',
    'password',
    'occupation',
    'email'
)

def create(self,validated_data):
password = validated_date.pop('password', None)
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance

def get_token(self,obj):
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
payload = jwt_payload_handler(obj)
return token

dense slate
#

I also don't see where you're trying to access values.

native tide
#

Somebody Here good with api´s

dense slate
native tide
#

i need a spotify api where someone can select a song and then the spotify code is sent to me

indigo kettle
#

spotify has an api

pallid lily
#

how do i update my python version from 3.9 to 3.10?

tacit wadi
pallid lily
#

thanks

pallid lily
#

A Good question in django models what is the difference between (ForeignKey and OneToOneField) in the two following models ```py
class RelationShips(models.Model):
user = models.Foreignkey(User,on_delete=models.CASCADE)
friends = ManyToManyField()
Category = ManyToManyField()

ClassRelationShips(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
friends = //
Category = //

golden bone
#

Like all such questions, it depends what you're trying to do. I would generally say that Django is complex and powerful, Flask is quicker and easier for simple projects

silver nexus
#

How to make a a button in flask that when pressed runs a function?

daring isle
#

Anybody know how to prevent duplicate static files being created in Django?

#

trying to present a random image from a folder but my static references dont include the duplicate files with weird extra nu,bers

#

i feel like its something to do with this:

STATICFILES_STORAGE = 'storage.whitenoise.CompressedManifestStaticFilesStorage'
#

a duplicate is being created when i run collectstatic . Not a problem when im explicitly naming the path/file in normal use, but if i pick a random name from the list it isnt lining up as the duplicate doesnt exist in my original static folder

inland oak
#

it makes the website loading forever even for one person

daring isle
#

I save my files in static , when I run collect static they get copied to staticfiles with duplicates

#

This is from settings.py

STATIC_URL = '/static/'

STATICFILES_STORAGE = 'storage.CompressedManifestStaticFilesStorage'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
#

This is my folder tree

#

im saving into static\practice_manager

trying to figure a way out on how to ref that list in my view without the extras

native tide
#

jinja2.exceptions.UndefinedError: 'bg' is undefined

dim rover
#

hello

#

@native tide

#

you are missing quotes

native tide
#

where

dim rover
#

filename='img/bg.jpg'

#

you see where?

native tide
dim rover
#

worked?

native tide
#

No

dim rover
#

now what?

native tide
#

error static is undefined

dim rover
#

what is static?

#

is that the name ?

native tide
#

folder name

dim rover
#

ok

lavish prismBOT
#

Hey @native tide!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

dim rover
#

put static in single quotes too

#

then try

native tide
#

yeah it's work Thanks Bro but

half osprey
#

Hey guys, Nice to see all you awesome people. Im looking for a python framework to build an ecommerce site! Idealy, one that allows users to submit their own picture so that we can print it onto something. Any suggestions on said framework?

dim rover
#

can you view developer tools

#

and see what resources are failing to load?

#

open it with F12 and hit refresh

#

they should show up red

native tide
lavish prismBOT
#

Hey @native tide!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

dawn heath
#

how can I send my ids from model , and brand vehicle to vehicleviewset in order to create a fk insert via api? https://dpaste.org/HVzF

inland oak
#

just request .pk value from your object

inland oak
#

it gives you quite DRY serializers to transform django model objects into jsons and back, including deserializers for easy revert operation

proven raft
#

hi

#

any idea of how to solve this problem of the websocket??

#

websocket._exceptions.WebSocketConnectionClosedException: Connection to remote host was lost.

inland oak
#

Then I would try to use Chrome Dev Tools and to check networking requests and any other debug information in order to find more detailed error

#

Also I would attach myself to backend console in debug mode and try to see any more detailed information

dim rover
#

yes you cam

#

why couldn't you?

#

please show your current model

proven raft
#

ok

vapid patrol
#

Hello guys, please I need help, I have been on it for days. Please help me

lavish prismBOT
#

8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.

vapid patrol
#

Ohhh. Sorry

#

How can I solve that?

inland oak
#

Ask specific questions for particular small stuff, right after you tried to find the answer on your own

vapid patrol
inland oak
vapid patrol
#

Okay.

inland oak
#

you just requested Authors from SQL database
and then you make repeated SQL request for each author

#

that makes intensive amount of requests to SQL and heavy slow down

#

you need to request necessary data in one request

#

author_list = Author.objects.order_by("book").count() you need to chain your request

#

with . until you make it accessing the right information you need

#

something like...

#

GetAllAuthors.JoinWithBooks(Where Book author matches author ID).AndGiveMeAllOfThem.WhileGroupingBooksToCountThemASNumberForTheEachAuthor

inland oak
#

Eh. I could write the answer in raw SQL, but ORM makes me confused how to write even simple stuff like that 🤔

#

ORM gives possibility to write raw SQL requests though

vapid patrol
#

Thanks for this.

inland oak
#

Tbh it is really hard to do without knowing raw SQL

#

I think it would be easier to go second choice

#

Second choice: writing Raw SQL request, which will smth like

ORM.makeRawQuery("SELECT Author.Name, Count(Book) FROM Authors \
Join BOOKS on Author.ID == Book.iD
Group By Book")
#

In order to do that all you need..

inland oak
worthy crest
#

but remember it's safer to use orm.

#

@vapid patrol

inland oak
worthy crest
#

however he has some knowledge for future

timid niche
#

Hello guys, I have a question. Would you say python would be a good choice to write a web app that would go onto websites and make a summary of the posts of said website that I can review/read?

dense slate
#

You can look into Beautiful Soup.

timid niche
# dense slate Yep.

Humm that's interesting I'll look into this and JS and weight the pros and cons of each languages for that , thanks !

native tide
#

any django queryeter here ?

dense slate
finite iris
#

good evening. A question for python-django experts: Because I have no knowledge in building rest apis - is it possible to fetch api data in python and request this data with react frontend? Main purpose of this would be to destructure to simplify access and also resell the gathered data

dense slate
#

Yea, sure it is.

#

Maybe there are exceptions, but you can really use any front-end framework to plug in to any backend API.

finite iris
#

but is it smart to build an api on top of another

dense slate
#

How is it one on top of another?

#

React requesting data from a python API is just one API.

finite iris
#

im requesting an api with django, destructuring it and build my own with the provided data

#

and provide this data to react

dense slate
#

Why not just fetch the data from the front-end initially?

finite iris
#

mainly for reselling purposes and also because I have huge datasets and figured out it could help to destructure it

dense slate
#

But yea I don't see why you couldn't do that.

finite iris
#

right now when i request i just get bulk of json data and it would be nice to make it available as single components

dense slate
#

Go for it. It's not a problem.

#

You're still just dealing with one API between your FE and BE

finite iris
#

yes I just thought of issues with speed

dense slate
#

Oh, well you just asked if it's possible. What issue with speed are you expecting?

finite iris
#

I was just brainstorming 😄

dense slate
#

You'll have to test it and see.

finite iris
#

I'll give it a shot

#

thank you

dense slate
#

It will of course increase time to get the data if you go from FE to BE to API and back again.

#

But how much time it increases is going to be dependent on multiple factors.

vagrant dagger
#

What database does django default use?

golden bone
vagrant dagger
#

There is

#

You can access users by the admin/

#

route

#

I use that for most of my project

#

s

#

Considering the fact that most of my projects are on the smaller side of the scale

#

I think there's a glitch with discord when if you type one letter even. It says you are typing

daring isle
#
class InvoiceForm(ModelForm):
    
    class Meta:
        model = Ledger
        
        fields = (
        #'branch_name', 
        'vendor_name', 
        #'account_no', 
        #'transaction_type', 
        'invoice_date', 
        'invoice_no',
        'transaction_amount',
        )
        #vendor_name = forms.ModelChoiceField(queryset=Vendor.objects.values_list('vendor_name', flat = True))

        widgets = {
            'invoice_date': DateInput(),
            
            'vendor_name':forms.ModelChoiceField(Queryset = Account.objects.values_list('vendor_name')),
            
            'invoice_no':forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Invoice Number'}),
            'transaction_amount':forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Amount'}),
            

        }
#

Anybody know how to get choices from a query into my form?

#

I did it through widgets before but now its not working

drifting radish
#

A secret key is required to use CSRF. Flask where can i send my key

daring isle
drifting radish
#

i have

drifting radish
daring isle
#

is that in your config file?

#

if its in your config change it to

"
drifting radish
#

`app = Flask(name)
db = SQLAlchemy (app)
bcrypt= Bcrypt(app)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['SECRET_KEY'] = 'SekretnyKlucz'
`

drifting radish
daring isle
#

if its in your app.py it should be good with app.config['SECRET_KEY'] =

drifting radish
drifting radish
#

this key

#

but where

daring isle
#

havent used flask in a while but dont think it matters - as long as its not in a function or trapped behind a loop

drifting radish
#

mhm

#

hahah

#

working

eager notch
#

Is there a really good Django tutorial out there? The official docs seem to be a little convoluted for my tastes...

dense slate
#

Django Girls Tutorial is great.

wary niche
#

I tried looking in to a Django Girls tutorial (since I am looking for a good beginner friendly tutorial) but wasn't able to find much. Any link you could provide ?

dense slate
viscid sparrow
#

i hosted my django app on heroku but the thing is that heroku's postgres db always resets when new commits are made
because of which old data gets lost
how should i fix this

dense slate
#

Host your DB where it doesn't reset?

#

Is that a heroku limitation for a free tier or something?

viscid sparrow
#

then all photos are lost

dense slate
#

No clue, sorry.

lilac solar
#

My hunch - I assume you are using an ImageField in Django. The database doesn't actually store the files just a reference to where they are uploaded. If this to a local filesystem then this is your issue. When a new commit (and therefore a deploy) happens within heroku, it will spin up a completely fresh dyno (which will have a fresh local file system) so your database doesn't know where they are. In fact they would have been deleted when heroku destroyed the old dyno.

Assuming the above is correct, I would recommend changing your Media Storage and associated settings to use S3 or similar (the django-storages library helps here), I would also recommend switching over your static settings so these are served more performantly.

manic crane
# dense slate Try to use the formatting here to make that easier to read.
    token = serializers.SerializerMethodField()

    email = serializers.EmailField(
        required=True,
        validators = [UniqueValidator(queryset=Occupier.objects.all())]
    )

    username = serializers.CharField(
        required=True,
        max_length=30,
        validators = [UniqueValidator(queryset=Occupier.objects.all())]
    )

    occupation = serializers.CharField(
        required=True,
        max_length = 30,
    )

    password = serializers.CharField(
        required=True,
        min_length=8,
        write_only = True
    )

    class Meta:
        model = Occupier
    fields = (
        'token',
        'username',
        'password',
        'occupation',
        'email'
    )

def create(self,validated_data):
    password = validated_date.pop('password', None)
    instance = self.Meta.model(**validated_data)
    if password is not None:
        instance.set_password(password)
    instance.save()
    return instance

def get_token(self,obj):
    jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
    payload = jwt_payload_handler(obj)
    return token```
topaz widget
#

So it looks like in a recent Django update, the WSGIRequest class was modified to remove, among other things, the is_ajax attribute.
Does anyone know what was put in its place to replace it? I have a contact form that is now breaking due to this update.

brazen laurel
#

I’m working on a flask app that interfaces with another 3rd party api that the user logs into with oauth. My plan was to use something like Flask-KVSession to store the oauth token in a serverside session instead of a client session, but looking through the change log and code it appears that the library uses pickle to serialize the session data before storing (https://github.com/mbr/flask-kvsession/blob/83238b74d4e4d2ffbdfd65c1c0a00ceb4bdfd9fa/flask_kvsession/__init__.py#L128). My understanding is that pickle is vulnerable to exploits in this case because the data is coming from an untrusted source. How can I work around this to just serialize the data to json. If I subclass this class and override the serialization_method property will that work? Or is it enough to just dump the data to a json string myself before setting it in the session?

lavish prismBOT
#

flask_kvsession/__init__.py line 128

serialization_method = pickle```
brazen laurel
#

Flask-Session does the same thing and uses pickle for serialization

daring isle
topaz widget
#

Well, if anyone is interested, I figured out the question I was asking about earlier. As of Django 3.1, the request.is_ajax method was apparently deprecated. Now that I am using 4.0, it appears to be completely unsupported altogether. Now, Django has pushed the responsibility of AJAX detection onto the dev. Here are the Django 3.1 release notes verbatim:

"The HttpRequest.is_ajax() method is deprecated as it relied on a jQuery-specific way of signifying AJAX calls, while current usage tends to use the JavaScript Fetch API. Depending on your use case, you can either write your own AJAX detection method, or use the new HttpRequest.accepts() method if your code depends on the client Accept HTTP header."

brazen laurel
fading gale
#

What do most people use for authentication / authorization in flask APIs?

#

Okta or something? Right now I’m messing around with LDAP and it’s hard

half osprey
#

Im guessing this is the place to talk about this.... I want to make a program that fetches me new facebook posts of a particuler person. Any advice on the framework to use? Im very new and building this will be how I learn.

golden bone
half osprey
#

@golden boneAwesome, thanks!

golden bone
inland oak
fading gale
#

Awe

#

I’m messing around with LDAP right now but I’ll just use normal SQL for logins later

inland oak
# fading gale Awe

Cookies for temporal storage of authenticated state
Cookies verified by encryption line verifying state by secret key

JWT cookies basically
In flask people have it named session I think

fading gale
#

I’m trying to replicate the Shell4j vulnerability for education rn

daring isle
#

anybody run a tailwind build recently? half of the classes are missing for me, and h1 tags arent rendering bold (New project)

daring isle
#

Heading elements are unstyled by default - just saw on the site .
The tutorials I’m following completely omit that point

delicate flax
#
from flask import Flask
from threading import Thread

app = Flask(__name__)

@app.route('/')
def main():
    return {"hello": "everything is ok"}
def run():
    app.run(host="0.0.0.0",port=8080)
def a():
    server = Thread(target=run)
    server.start() 

Showing invalid identifier error?

orchid olive
#

i have a

TexPassword = PasswordField('Password:')

i set the value

Form.TexPassword.data = 'SomeEncryptedText'

display the form

{{ Form.TexPassword(class="form-control") }}

but i get an empty TexPassword in the web page instead asteriscs

what have i miss?

mystic vortex
#

i wanna render <reason> in a page but after reendering the page its not visible cause the browser is thinking that <reason> is a tag but it is not, instead i wanna render it like <reason> in the html page

native tide
mystic vortex
eternal blade
#

I have this signal to dispatch an event when a new message is created ```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,
            },
        )

this is the `consumers.py`py
import json
from channels.generic.websocket import WebsocketConsumer

from api.serializers import UserSerializer

class ChatConsumer(WebsocketConsumer):
def connect(self):
user = self.scope["user"]
self.channel_name = f"User-{user.id}"
self.send(text_data=json.dumps(UserSerializer(user).data))

def disconnect(self, close_code):
    pass

def chat_message_create(self, event):
    print("Created")
    self.send(text_data=json.dumps(event["payload"]))``` and when I create a new message in the admin panel the signal gets called but it does not get dispatched through the websocket, and any debug prints in `ChatConsumer.chat_message_create` won't even get printed.

Thanks in advanced

soft heart
#

how do you get variables from client side js

to python server

vagrant dagger
#

Yes, it has django now

#

It is also a very nice resource for html, css, js or node.js

soft heart
inland oak
#

and GET/POST requests query parameters

#

also sticky cookies technically carry data between clientside/serverside too

deft shore
#

Hello! Does anyone have a tutorial on how to handle authentification with Django (backend) and React (frontend)?

inland oak
native tide
#

regarding filters.SearchFilter in django, is it possible to include object ID in search_fields?

fallen mango
#

I have a django+react application which is hosted using nginx and gunicorn. Although the page load is working properly and server has good amount of CPU ,RAM and memory but the queries are taking a long time to respond when there is a some traffic on the website. Can anyone help how to cache or change some configurations in nginx or gunicorn so that it could be handled?

tight ocean
#

Any idea on how to plot perpendicular lines to Y axis?

#

Like this

#

In matplotlib

hollow minnow
fallen mango
fierce grail
#

hi can anyone help me wtith JQ

#

i want to replace the body of my webpage with the "new" data from an ajax post , but i do not want to include a div with an id of navBarID

#
       success: function (data) {
           $("body").html(data);```
#

that is what i have now atm, it just replaces the whole body with the whole of the html code which messes up other parts of my code, so i wanna just replace everything except the div with id navNarID

#
       success: function (data) {
           var responseDataNav = $('body : (#navBarID)',data).html();
           $("body").html(responseDataNav);```
#

i have done this which seems to work. however im not sure if the nacvbar is still being replaced

#

as my problem stands, when i replace the whole body, my navbar dropdown function stops working, this doesnt happen when i replace ONLY the relevant thing (table) that i want updated visually , i canot do that way as the response (data) has some extra lines of html code which is needed , hence why ive been stuck replacing the whole body

native tide
#

Are these type of queries safe againts sql injection? I tried escaping the values with the markupsafe module, but that changes the data type and to markup and I don't think I can use that in my queries. Maybe I can convert the result to string but idk if it the value will stay escaped xd

thorn igloo
native tide
manic crane
#

someone please help => from .views import RegisterAPIView
ImportError: cannot import name 'RegisterAPIView' from partially initialized module 'Occupier.views' (most likely due to a circular import) (/Users/samuelihuoma/Desktop/occupy/backend/Occupier/views.py)

native tide
#

is there any way to access kubernetes cluster through django

inland oak
#

By any chance you have no idea what k8s is, right?

#

Anyway, that's possible of course, but what would be the point? 🤔

#

Oh right. There is a point. To raise temporal instances of smth for particular users for example

#

k8s tutorial works in this way i think

thorn igloo
native tide
#

I don't want to deploy the whole application in a cluster

#

just the model

#

I know you can host a model on k8s, but I have no idea how to make calls to it so that I can access the model, make predictions, and return results

#

through django, I can do this through the command line of the google cloud platform

native tide
inland oak
#

essentially not really a big difference from regular server

#

So as long as your application can be wrapped to docker container and running statelessly with it, k8s is your friend

native tide
#

yeah so I'm going to wrap the model in a docker container, but the question is, how can I send requests to the container in order to generate predictions

#

the only examples I've seen have used curl in the google cloud command line

tulip shoal
#

Any requests / beautifulsoup4 experts around? Trying to figure out why I can't touch zara or hm, always getting the access denied no matter the header I use.

autumn veldt
#

why whan i loading an img with a clear background with PIL it load it up like it has white background ?

this is the code:

from PIL import Image

s= Image.new("RGB",(255,255),color=(255,0,255))
s.paste(Image.open("h.png"),(0,0))
s.show()


h.png is the img with no background

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.

tulip shoal
#

@inland oak what that sir?

#

Oh, is parsing ilegal?!

inland oak
tulip shoal
#

It's per TOS / research purposes

#

I have no problem deleting the question, but keep in mind that an open web benefits all

autumn veldt
inland oak
tulip shoal
#

In the same way that closing it behind stuff like url shorteners is against everyone's benefit

#

You do like Zara a lot, don't you? :))

vague yacht
#

hello hello
we generally don't allow helping with webscraping projects, unless the site specifically permits it in its ToS

inland oak
vague yacht
#

so, please do not discuss your project here

tulip shoal
#

It's not a project, was just curious how a website can block access w/ the right user agent

#

Which I don't think is a breaking-the-law question tbh.

inland oak
vague yacht
#

let's move on to some other topic please

tulip shoal
#

I'm in awe, learning and all 🙂

autumn veldt
inland oak
#

Indeed. Question, last few months I worked on a web site.

#

I made two different versions of its interface

#

could you evaluate which one is better?
I am a bit incomfortable to drop link to public, I'll write url to DM if not a problem
it is relativelly small web site out of just three pages.

vague yacht
autumn veldt
#

ho

#

i didnt see im on web dev

#

sry

eager notch
#

Is Django even useful if I like writing custom queries and deserializing them to Python objects?

manic crane
#

can someone help with this please ? => raise TypeError('view must be a callable or a list/tuple in the case of include().')
TypeError: view must be a callable or a list/tuple in the case of include().
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('rest_framework.urls')),
path('api/', include('Occupy.urls', namespace='home')),
path("api/","Occupier.authentication")
]

late fjord
#

Guys is it possible to learn to make a native app in a month

#

for someone who has an understanding of programming

#

and some beginner experience with django, ccs, html, fastapi

daring isle
#

trying to get to grips with tailwind, how do i make my sidenav the whole page and overlay. its currently just popping in above r below text

#

you might be able to help, since you're the tailwind guru

thorny rover
#

but there are lots of ways to do it, many i'm sure better than mine haha

#

Thats a link to a rough idea on a way to do that with tailwind

daring isle
# thorny rover but there are lots of ways to do it, many i'm sure better than mine haha

Where would i crowbar that into?```
<div class="min-h-screen w-full relative">
<input id="my-drawer-3" type="checkbox" class="drawer-toggle">

  <div class="drawer-side fill screen w-full border-8">
    <label for="my-drawer-3" class="drawer-overlay screen w-full"></label> 
   
    <ul class="p-4 overflow-y-visible menu h-full w-80 bg-base-100 fill screen">
      <li>
        <a>Home</a>
      </li> 
      <li>
        <a>Practices</a>
      </li>
    </ul>     

    </div>

</div>

daring isle
#

i should mention - im using daisyui for tailwind

#

only because i couldnt find anything that does what i need in standard

native tide
#

how to fix this err when i import url

#

from django.urls import url

#

help

thorny rover
#

unless something like Diasy or your frontend framework if you have one has that functionality

strange moat
#

Django url file

thorny rover
#

HeadlessUI is great

daring isle
thorny rover
#

But I would think its better to do it more from scratch so you know you can before offloading it

thorny rover
#

it can be tempting to load in a ton of extra libraries and frameworks but unless theyre really needed and make things better for that exact project you'll want to use a few as possible in general

daring isle
#

most of them i loaded in for a single button lol

thorny rover
#

Personally my base stack is just html / css / js / vue / tailwind
edit: also Vite

daring isle
#

my first django project, and already deployed to end users - oops

thorny rover
#

i only add things on past that if i need them

daring isle
thorny rover
daring isle
daring isle
daring isle
calm plume
#

Are you using a JS framework?

daring isle
#

i've hit a ceiling i think, i'll learn js properly next

calm plume
#

Oh, then yeah, Headless UI won't work.

daring isle
#

its an internal site just for crud operations to a mysql. It got as fancy as a couple of collapsibles....... and then i needed a graph, and then i designed it for mobile with a bottom nav and notification badge, and then i wanted fancy buttons....

its all my own fault

thorny rover
#

ew, Jquery? @daring isle wash your hands

#
1. jQuery is a legacy library. Standardized features like querySelector, CSS animations, and fetch make many of its features obsolete.
2. Using jQuery over standard features is a waste of bandwidth.
3. Because jQuery is so bloated, using jQuery often means using jQuery for everything, which means you learn less about standard web development.
4. jQuery has fallen out of fashion, and full frameworks (React, Angular, Vue) are more popular.
5. With modern frameworks you declare a state and your UI reflects your state. Rather than with jQuery having to manage both the state and the UI all at the same time.
6. jQuery's cross-browser support can be substituted with the few polyfills you actually need. This also makes it easier to update when features become better supported.
7. If you really just want a shorthand for querySelectorAll, consider bling dot js```
daring isle
#

😩

thorny rover
native tide
terse vapor
#
@app.route('/check/<string:subid>')
def gifts(subid):
    q = Detail.query.filter_by(subid=subid).all()
    return render_template('check.html', q=q)

I created a function that allow all child object can be returned with <p>{{ q.name }}</p> however, when I opened the site, nothing showed up, how can i fix it?

terse vapor
#

its just <p></p>

frozen girder
#

<p>{{ q.name.__repr__() }}</p>

terse vapor
#

it returns Undefined 😅

frozen girder
#

err, None?

daring isle
#

do i need to "convert" my django project to rest if i want to use react in it?

terse vapor
#

<html>
    <p>Undefined</p>
</html>
cloud locust
#

Hi, I'm running a Flask site with Nginx and Supervisor (to run in background). Lately, I've been having issues with the web server recognizing changes to any of the Python, HTML, CSS, or JS files.

Whenever I work on my site on my machine, I run it using the debug option on localhost. Everything works perfectly fine, and I see it in real time. But whenever I push it to my remote server, the website does not process any of the changes made to it. For example, I've recently created a new route within Flask. On the live server, those webpages are "not found".

And yes, I'm reloading everything correctly.sudo systemctl restart nginx sudo supervisorctl reloadIf it helps, I think the problem has started ever since I've added an SSL certificate to my site. No idea if it correlates at all, but it helps me figure out what changed to make it not work.

Thanks in advance for helping me!

inland oak
#

but in general I would recommend converting to rest, as it is the best and easiest approach IMO

#

some people would disagree with me though

#

btw, if you plan to have a lot of endpoints (more than 20-30?), there could be a point for graphql approach instead of rest.

native tide
native tide
#

like previous on left and next on right

serene prawn
inland oak
serene prawn
#

Both approaches are great and you can expose both REST and GraphQL API in your app

serene prawn
native tide
#

How to deploy my ml model in flask

inland oak
#

All right, so you spoke about SQL normal databases too

serene prawn
inland oak
#

which allows to remove a lot of REST endpoints and having them all united into one

serene prawn
#

With graphql you can just write a query for that, but with rest it's either making 3 calls - to fetch users, his posts and post comments or making a specific endpoint that would return everything in one go

inland oak
#

and in some cases just user and his posts
or in some cases user and his comments, and e.t.c.
With graphQL is is DRYed into one endpoint, potentially just less code to have for all of it

serene prawn
#

It's not necessarily more dry but you just don't have to make multiple http calls and join that data on your frontend

inland oak
serene prawn
#

Ideally you should learn both, imo it's easier to write mutations using rest rather than graphql

#

Plus if you expect people using your api programmatically it's in most cases easier to do using rest

inland oak
#

rest is only single endpoint purpose approach?

#

or it can include jsonapi approach

serene prawn
#

json:api is built on top of rest and makes it easier to fetch relational data, but it's easier to use graphql for that

native tide
#

where i add ipynb file in flask static or templates

inland oak
serene prawn
#

Kinda, you can look at the spec and see 😅

inland oak
vernal moat
#

How can I remove the right arrow at the bottom?

vernal moat
#

its showing up in all my pages

inland oak
#

i was confused to search it at the right, while it is at the left

vernal moat
#

?

#

So how can i remove it

inland oak
#

so let me assume that you just have an image then

#

then removing it is just a matter of using photoshop or even simple paint program

#

https://photopea.com here is online photoshop program for you

buoyant geode
#

HI I am trying to implement copy to clipboard in my Django app and when I did so am able to copy only a single word from the starting of sentence please some help me regarding this
main.js

#
console.log(copyBtns);
copyBtns.forEach((btn) =>
  btn.addEventListener("click", () => {
    const value = btn;
    console.log(value);
  })
);```
#
      {{ post.date_posted|date:"F d, Y" }}

      <button  class="btn btn-outline-primary ctrl-btn" post_data = {{ post.content|cut:' ' }}>copy</button>
    </div>```
#

<button class="btn btn-outline-primary ctrl-btn" post_data="Eratexpetendadefinitionemideos.Sempersuscipiteumut,eumexnemorecopiosae.Namprobatuspertinaciaeu!Noaliivoluptuaabhorreantnec,teproimpeditconcludaturque,inseamalistorquatosdisputationi!Namtealiinobisponderum,eifugitaccusamuspro." conguesalutandiexeam!meianprimaconsulatu,eratdetractoeuquo?vimeaesseutinamefficiantur,atnosterdicunt.="">copy</button>

#

when I try to print this some of the data is missing please help me with this

#

const value = btn.getAttribute('post_data')
I only get
"Eratexpetendadefinitionemideos.Sempersuscipiteumut,eumexnemorecopiosae.Namprobatuspertinaciaeu!Noaliivoluptuaabhorreantnec,teproimpeditconcludaturque,inseamalistorquatosdisputationi!Namtealiinobisponderum,eifugitaccusamuspro."
rest of the data is missing please some one help me with this

autumn veldt
#

how do i show an image in flask ?

inland oak
vernal moat
#

Whats this?

#

nvm thanks

autumn veldt
#

@cerulean remnant u see ?

cerulean remnant
#

yes

autumn veldt
#

why is it look like this ?

cerulean remnant
#

the image is not being loaded properly

#

you did smth wrong-

autumn veldt
#

in the py code ?

cerulean remnant
autumn veldt
#

this is the code :

@app.route("/img/<path>")
def img(path):
    return f'<img src="{path}">'
#

(flask)

#

it runs on replit btw

cerulean remnant
cerulean remnant
autumn veldt
#

do you know how i do that with os ?

cerulean remnant
cerulean remnant
#

i gtg-

autumn veldt
#

ok

autumn veldt
#

whats gtg

#

ho

ornate storm
autumn veldt
autumn veldt
#

@lament otter

lament otter
#

Pls zoom it

autumn veldt
#

i cant

lament otter
#

Hmm

native tide
lament otter
#

Ok I help

native tide
#

where do u need to help?

lament otter
#

Listen did u make a index.html?

autumn veldt
autumn veldt
autumn veldt
native tide
autumn veldt
#

i dont know what is template injection

native tide
native tide
autumn veldt
native tide
#
allowedPath = ["img1.png", "img2.png"]
if not path in allowedPath:
    return "Path not allowed"
native tide
autumn veldt
#

this server is for my discord bot

lament otter
#

?

autumn veldt
#

i want to show images on the server cause discord.py embed dos not support files only urls

native tide
autumn veldt
#

like a file folder

native tide
#

yes

autumn veldt
#

ok but than what

native tide
#

then you will be able to see the images

autumn veldt
#

the discord bot and the server and the images are in the same folders

#

but

#

whan i run the server

#

i need to show me the img

#

but

#

it shows a small icon

native tide
#

if the size icon is as small as icon size it's ok

autumn veldt
#

not like this

#

you see this ?

#

this is not my img

#

idk what is this

#

and its really small

#

this is the hole website

#

it need to show an img but it shows me this

native tide
#

send the url you use to open that

autumn veldt
#

the img is watchable i opened the img

#

you mean this ?

native tide
#

look at the source code

#
<img src="mc.hypixel.net.png">
#

what's mc.hypixel.net.png?

autumn veldt
#

?

native tide
#

it's not an image

autumn veldt
#

its an img

#

that

native tide
#

ok

autumn veldt
#

with the same folder with the server

native tide
#

it's xss vulnerable too

autumn veldt
#

wdym ?

#

i dont know whats that

native tide
native tide
manic crane
#

im trying to login in my DRF api thru postman and it even says that my user exists but when i try and login i get => {
"message": "Invalid credentials, try again"
}

autumn veldt
#

idc

native tide
#

you should know something of web security before of make web application

autumn veldt
#

cause its just for my bot

manic crane
#
    #authentication_classes = ()
    #permission_classes = ()

    serializer_class = LoginSerializer

    def post(self,request):
        email = request.data.get('email',None)
        password = request.data.get('password',None)

        occupier = authenticate(username=email, password=password)


        if occupier:
            serializer = self.serializer_class(occupier)

            return response.Response(serializer.data, status=status.HTTP_200_OK)
        return response.Response({"message":"Invalid credentials, try again"}, status=status.HTTP_401_UNAUTHORIZED)```
autumn veldt
#

and im not running this no my pc

#

so it really meter ?

native tide
#

still if you was running that on your pc XSS attacks aren't able to attack the server

#

while SSTI are able to attack the server

eager notch
#

Is there a great tutorial that describes how to use Django’s templates with a client side framework?

I really miss the ergonomics of server side rendering. But definitely see the benefits of a client JS framework.

vernal moat
#

Hello Im using this svg: https://pastebin.com/xL0ixf2w
Im getting an error: error on line 38 at column 26: Comment not terminated

#

ig ill just use a png

inland oak
#

Next.js for React, Nuxt.js for Vue.js and e.t.c.

thorn igloo
#

like regular js

#

react too if i remember correctly

#

that way you can still use django to render your templates but have some parts of your app be reactive i guess

exotic hinge
#

I'm trying to use selenium to get the text of this svg element, but self.driver.find_element(By.CSS_SELECTOR, self.level_path).text doesn't work
https://imgur.com/RQFRJJY

#

it just returns an empty text

#

it gets the svg element, but idk how to get the title

eager notch
#

I guess I’m asking if using Sever Side rendering with Django is somewhat mutually exclusive from using a client framework

#

I mean I can imagine it’s possible. But is it an uphill battle

serene prawn
#

Django provides admin app that uses template rendering and you can still build api's using django 😃

inland oak
#

can't say for other frontend frameworks for sure

daring isle
#

anybody know how to center the hover box in react?

#
.nav-text a {
    text-decoration: none;
    color: #f5f5f5;
    font-size: 18px;
    width: 95%;
    height: 100%;
    display: flex;
    align-items: center;
    padding: 0 0px;
    border-radius: 4px;
    background-color: #1a83ff;
  }

One of these SOBs is causing it since i put the background on and its the same if not hover

eager notch
inland oak
#

then its hover will be centered too

daring isle
#

thanks man

eager notch
#

Hmm, it looks like alpine.js fits my needs

serene prawn
eager notch
#

No one said I do. But sometimes the ergonomics of server rendering are really enticing.

serene prawn
#

template rendering can be good if your project isn't big, e.g. a blog or something similar

#

But for larger project i'd use a frontend framework, (Angular, Vue, React...) since it allows for better code separation between your frontend and backend

#

And are easier to work with in general imo

granite maple
#

there's an extremely simple php-driven website I use as an image host. I'd like to automate the process of logging in and uploading an image. the web automation frameworks I've found (selenium, cypress) seem to be very over-engineered for this purpose. does anyone know of a simpler alternative that could navigate a login control and that's about it? there isn't even any javascript on this page

frozen girder
granite maple
#

bash is evil 😄 but maybe I can replicate it with requests

frozen girder
#

i agree with you 😄

dense slate
#

You should probably ask a question.

#

But you are missing an in for what it's worth.

dark night
#

Will I run into issues if I have all my flask api endpoints in the same file? Is there a standard people follow for organizing the backend in python?

native tide
golden bone
cinder girder
terse vapor
#

how can I access all child object under one parent object with flask sqlalchemy?

native tide
#

My model is not deploy on flask

#

model=pickle.load(open('model.pkl','rb'))
ModuleNotFoundError: No module named 'sklearn

lavish prismBOT
#

Hey @native tide!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

#

Hey @native tide!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

#

Hey @native tide!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

#

Hey @native tide!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

dim jay
#

Your message is too long, please read the message from the bot instead of resending it

native tide
#

showing sklearn error

native tide
#

@native tide <h1 style="text-align:center"><u>PROJECTILE MOTION CALCULATOR</u></h1>

i want to add color style too how can i do that?? im so smh grumpchib 💢 im figuring out for so long

#

Ok

#

do you have a css file?

native tide
#

you will need a css file or a css framework

#

recommend going with file for now

native tide
#

...

#

that's not a framework

#

output

#

@native tide

#

Ok

#

all i want to do is add color too the heading

#

<link rel="stylesheet" href="style.css">

#

add this line

#

here somewhere

#

done

#

then

#

create a file called style.css

#

in the same folder

swift wren
#

what is a way that flask and react can have authentication, i mean ik how flask login works but idk how it would work if you login a user using flask by sending login info from react frontend and authenticating it through flask but idk how to sustain that if im using react. how could those login_required restrictions apply to the frontend as well

thorn igloo
inland oak
#

Not really understood what you are saying

#

perhaps you could draw simple sketch in paint/photoshop of what you are trying to achieve

#

wait a second, perhaps I start to get

#

are you wishing to make them drag and droppable by mouse? or by clicked buttons? or by pressed keyboard buttons?

#

with relocating to switch their places?

#

Well, obviously that involves using javascript, the easy way would be to have frontend framework to write it

#

the painful way would be to use vanilla JS

#

semi painful way would be JQuery

#

frontend frameworks make it way easier and with less code ¯_(ツ)_/¯

#

Vue.js for example

#

probably React should be easy too

#

Vue.js is the simpliest to learn out of modern production ready frameworks

#

everything depends on the learning speed, but consider usually a week to get into the flow

#

Technically it is written being possible to learn from few hours to one week, but it surely took me a week

#

because i learned frontend from zero

#

MM yeah, but preferably start to use Vue.js 3 already

thorn igloo
#

you can do the same with react

#

they explain it in the docs

#

here's a link

dusk portal
#

@thorn igloo can u help me deploy my django application on a vps hosting

thorn igloo
#

never used django in my life

dusk portal
#

im stuck from a week

#

or more

dusk portal
thorn igloo
#

yes

dusk portal
#

i just need help in pointing domain @thorn igloo

#

plz bruh

thorn igloo
#

if i said i knew how i'd be lying

dusk portal
#

im not asking django

thorn igloo
#

i've just use the cheap cpanel hosting, does almost everything for me

dusk portal
#

ohh

thorn igloo
#

yeah i get what you're asking

dusk portal
#

yeah

#

the thing is

#

in my hosting the site is live

#

how can i host it on domain

thorn igloo
#

maybe try this

#

additional help here

inland oak
#

to point AAA records to your IP address

dusk portal
inland oak
#

well, and to buy certificates

#

and to apply them at your VPS with Nginx

dusk portal
#

we bought it from godaddy

inland oak
#

as cheaper alternative

#

instead of buying certificates

dusk portal
#

we bought domain from godaddy
n hosting from Hostinger vps hosting

inland oak
#

it is for Certificate

#

domain is still required anyway

dusk portal
#

ik

inland oak
#

Oh forgot to mention

dusk portal
#

we bought it

inland oak
#

There is FREE TO USE option for domains!

#

there are services that provide subdomains for free)

dusk portal
#

@inland oak can i get ur 5 mins?

inland oak
#

not rembmering from the top of the head their name

#

but I remember they provide like 16 free sub domains

dusk portal
#

ohk so the thing
i just made a directory then dumpted the zip n unziped n at startup file i toom wsgi so my hosting started running

#

idk why i cant point the domain

oak sky
#

what is the best way to access variables from the "main" flask file in a blueprint file?

#

oh

#

sorry to interupt

inland oak
oak sky
#

in this case its hcatcha instance

#

but yeah

#

mostly config variables

opaque rivet
# dusk portal ..

Setup your app on a server with nginx forwarding the request from port 80 (or 443 if you have https) to your backend.
Find the IP address of your server.
You can then go to the settings of your domain on goDaddy, and add an A record (which is the IP address of your server). When someone visits your domain, the IP will be resolved from the DNS and they will make a request to your server's IP address.

inland oak
# oak sky mostly config variables

config variables are injected in flask into app instance
and those vars are available with special flask import config through the applcation

#

python intance objects are imported in the same way as python objects are imported in general. absolute or relative imports.

dusk portal
oak sky
#

so i just do from main import app?

#

or am i being stupid

dusk portal
inland oak
oak sky
#

np

opaque rivet
#

No clue what I'm looking at, I would personally just do it myself instead of having a manager unless you understand exactly what that manager is doing

dusk portal
#

plz guide me

#

what i can do next

opaque rivet
#

okay cool, so it looks like you have an A record setup to map your domain to your server's IP address.

#

Now setup nginx

dusk portal
#

ohk how

opaque rivet
#

Watch some videos/guides online and learn nginx

inland oak
# oak sky np

example taken from here https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xxiii-application-programming-interfaces-apis

config.py

import os
from dotenv import load_dotenv

basedir = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(basedir, '.env'))


class Config(object):
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', '').replace(
        'postgres://', 'postgresql://') or \
        'sqlite:///' + os.path.join(basedir, 'app.db')
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    LOG_TO_STDOUT = os.environ.get('LOG_TO_STDOUT')
    MAIL_SERVER = os.environ.get('MAIL_SERVER')
    MAIL_PORT = int(os.environ.get('MAIL_PORT') or 25)
    MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS') is not None
    MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
    MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
    ADMINS = ['your-email@example.com']
    LANGUAGES = ['en', 'es']
    MS_TRANSLATOR_KEY = os.environ.get('MS_TRANSLATOR_KEY')
    ELASTICSEARCH_URL = os.environ.get('ELASTICSEARCH_URL')
    REDIS_URL = os.environ.get('REDIS_URL') or 'redis://'
    POSTS_PER_PAGE = 25

the config file is injected into app instance in __init__ at almost source code root, download the project files and check for yourself

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

Then you import in any app file and accessing it through the flask library

from flask import current_app
current_app.config.get('SQLALCHEMY_DATABASE_URI')
oak sky
#

ty

inland oak
#

Django user for a year already but still remembering it

#

heh and I thought my memory is bad

dusk portal
#

now whats the use of nginx

opaque rivet
#

that's for you to find out

inland oak
# opaque rivet Watch some videos/guides online and learn nginx

or even better, there is Nginx free O'Reilly book distributed by Nginx company!
https://www.nginx.com/resources/library/complete-nginx-cookbook/

opaque rivet
#

beautiful

inland oak
#

makes me loving for that

#

that's not the only one book they have for free

serene prawn
inland oak
#

web application security is good to read and few other books are also provided there for free

serene prawn
#

But it depends on your needs i guess since traefik is just a reverse proxy

inland oak
#

nginx can work like that too, but some stuff is locked behind paid verison

#

dedicated tools can be better than general purpose nginx

inland oak
#

like using Haproxy for loadbalancing, instead of Nginx where almost all load balancing is locked out

serene prawn
#

Yep, community edition can't cache anything but often you can control cache on server side or on client side (using http headers)

inland oak
#

I mean i was able to setup server side caching to cache REST api endpoint from my python web server

#

that's good)

serene prawn
#

Docs point to traefik enterprise though 🙂

serene prawn
dusk portal
#

@serene prawn still idk why it isnt pointing on the Hostinger vps hosting

#

but yeah site is running

serene prawn
#

What exactly doesn't work? 🤔

dusk portal
opaque rivet
#

thats not specific is it

drifting radish
#

where can i open my datebase app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db' app.config['SECRET_KEY'], = 'thisisasecretkey'?

inland oak
drifting radish
#

Better use SQLAlchemy or sqlite3?

#

or admin php

jovial cloud
drifting radish
slim skiff
drifting radish
#

aha

slim skiff
drifting radish
#

using SQLAlchemy can i conecct with Sqlite3 ?

slim skiff
drifting radish
#

okey

signal iris
#

i don't consider the following problem as an error, so i'm writing here.
My Django app's file structure is:

.
├── api
│   ├── db.sqlite3
│   ├── debug.log
│   ├── __init__.py
│   ├── manage.py
│   ├── products
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   └── __init__.cpython-39.pyc
│   │   └── v1
│   │       ├── admin.py
│   │       ├── apps.py
│   │       ├── __init__.py
│   │       ├── migrations
│   │       │   └── __init__.py
│   │       ├── models.py
│   │       ├── __pycache__
│   │       │   ├── admin.cpython-39.pyc
│   │       │   ├── apps.cpython-39.pyc
│   │       │   ├── __init__.cpython-39.pyc
│   │       │   └── models.cpython-39.pyc
│   │       ├── tests.py
│   │       └── views.py
│   ├── __pycache__
│   │   └── __init__.cpython-39.pyc
│   ├── requirements.txt
│   └── selloff_drf
│       ├── asgi.py
│       ├── config.py
│       ├── database_config
│       │   ├── db_config_dev.py
│       │   ├── db_config_prod.py
│       │   └── __pycache__
│       │       └── db_config_dev.cpython-39.pyc
│       ├── __init__.py
│       ├── __pycache__
│       │   ├── config.cpython-39.pyc
│       │   ├── __init__.cpython-39.pyc
│       │   ├── settings.cpython-39.pyc
│       │   ├── urls.cpython-39.pyc
│       │   └── wsgi.cpython-39.pyc
│       ├── settings.py
│       ├── urls.py
│       └── wsgi.py
└── client

models.py:

class Category(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField()

    class Meta:
        ordering = ['name']

    def get_absolute_url(self):
        return reverse('products:category_list', args=[self.slug])

    def __str__(self) -> str:
        return self.name

When I try to make migrations, Django writes the following: No changes detected in app products. Please help

#

i also have my app's name in INSTALLED_APPS

drifting radish
serene prawn
# drifting radish using SQLAlchemy can i conecct with Sqlite3 ?

sqlite is one of many relational database management systems aka RDBMS, it's responsible for storing/querying your data from the disk
SQLAlchemy on the other hand is a ORM, in short it helps you to use rdbms by writing python code instead of sql, though sqlalchemy queries written in python code are very similar to sql in structure.

#

SQLAlchemy can be used with most of the rdbms, including sqlite 🙂

serene prawn
#

You can write query like this using sqlalchemy:

query = select(User).filter(User.username == "AquaCherry")
user = sesion.scalar(query)

And it would be translated to SQL query depending on dialect (sqlite, mysql, postgres, ...)

select user.id, user.username from users where users.username == "AquaCherry";
drifting radish
#

aha

#

you recomened flask or django?

serene prawn
#

it depends

drifting radish
#

online game

serene prawn
#

That's really vague 🙂

drifting radish
serene prawn
# drifting radish it depends what

All frameworks are good for certain things, e.g. Django has built-in authentication and good for building simple-medium complexity applications, but i personally wouldn't recommend using it for building API's, FastAPI would be a better fit for building API's, but it doesn't have built-in features like authentication, admin panel and orm, so you'd have to build/choose solutions for that, e.g. fastapi-users for auth and SQLAlchemy as an orm

#

And flask is just obsolete because of fastapi 😛

drifting radish
#

a okey

#

`AttributeError: 'LoginForm' object has no attribute 'validate_on_sumbit'

`

inland oak
serene prawn
inland oak
serene prawn
#

Fore me it's vice-versa, drf is hard to implement new features with, though initial setup is easier with django

#

If we're not talking about simple crud

inland oak
#

tbh, I am a bit eyeing fastapi to try. But well... there are multiple other technologies to learn more important first. finally got started with kubernetes.

serene prawn
#

Also django orm is not an opt-in and i don't really like it

native tide
#

I have a project where I'm using django and react and connecting them using graphQL. I have an async function call in django, can I display two different views in react for when the async is processing and after it is done?

inland oak
native tide
#

how would I do it?

inland oak
native tide
#

about 15 seconds

inland oak
#

Your backend does some lengthy job then

native tide
#

yes it is a machine learning process

inland oak
#

I would recommend applying Celery then

serene prawn
#

Probably could set some kind of state or fire an event before sending your request and do the same after it completed

native tide
#

ok I was looking into that

#

celery that is

inland oak
#

First request launches job in celery and returns task ID

serene prawn
#

What does it has to do with celery really? 🤔

inland oak
#

Then... Ideally you use web sockets
Not ideally you make repeated requests to chheck the job done

inland oak
#

To load balance it

native tide
#

ok but how would I call the view in react

serene prawn
#

The question wasn't about that though 😅

inland oak
#

He does not know that he does it though

serene prawn
#

@native tide if i understand correctly you want to display some kind of loader while your request is being processed?

native tide
#

yes

#

and my frontend is done entirely in react

#

so I would like to keep it that way

serene prawn
#

What library are you using to connect with graphql api?

native tide
#

graphene

serene prawn
#

On your frontend i mean

inland oak
#

Just display one thing
Then start request and when finished display another one

native tide
#

axi9os

inland oak
#

I would recommend to toggle animation that does smth 15 seconds

native tide
#

axios

serene prawn
#

Ah, so you're not using graphql-specific library like apollo?

native tide
#

well It doesn't always take 15 seconds

#

no wait I am using apollo I'm sorry

serene prawn
#

😐

night dew
#

👀 anyone got any idea on why uwsgi would complain modulenotfound: wsgi? the config is properly done following the docs and its a django app

native tide
#

my bad I forgot, this project has been on the backburner for a while now

native tide
serene prawn
#

I'm not an react expert, i mainly used angular + rxjs, but i think you could do something using hooks 😅

inland oak
native tide
#

but can both views be handled in react

serene prawn
#

Actually apollo already provides loading flag 👀

function Dogs({ onDogSelected }) {
  const { loading, error, data } = useQuery(GET_DOGS);

  if (loading) return 'Loading...';
  if (error) return `Error! ${error.message}`;

  return (
    <select name="dog" onChange={onDogSelected}>
      {data.dogs.map(dog => (
        <option key={dog.id} value={dog.breed}>
          {dog.breed}
        </option>
      ))}
    </select>
  );
}
native tide
inland oak
#

Most used for sure

serene prawn
#

Yeah, react is certainly more popular

inland oak
#

Hehe angular guys

#

I am Vue follower ;b

serene prawn
#

I like angular

native tide
#

I like it too, but I think I will be using react mostly from now on out since my friends that I work on projects with like react as well

#

they are sworn angular haters

serene prawn
inland oak
#

And I will try to be not doing frontend next time perhaps. I wish to be more backend and infrastructure guy

#

Frontend is a bit not comfortable for writing tests. Well... Actually it is easy to write tests .. but still... Meh

dusk portal
#

@inland oak

#

im on a vc ft a dude from an hour almost done

#

ModuleNotFoundError: No module named 'wsgi'

#

thats the thing that is left

#

everything is installed up to date
venv is also activated
n all the modules are there (pip freeze op)

#

we're using uwsgi (same issue was there while we were using gunicorn)

native tide
#

I am almost 100 percent sure that this is causing the error

drifting radish
#

Who can help

#

Me

daring isle
#

Just learning djang rest framework and react .
Is the class based view the only or best way ?

In my normal django projects I avoided classes anytime I could and didn’t have any issues

#

Is it a problem for react if things aren’t defined within classes ?

orchid olive
#

in flask, how can set de value to a passwordfield?

#

Form.Password.Data = "abcde"

live the Password object in blank

swift wren
#

hey guys, im trying to post information from react to flask
but it doesnt post at all
ik the api is working because if i post using postman it works, but if i post using axios it doesnt work
this is my axios code

function postLogin(username, password){

    console.log(`you posted with ${username} ${password} `)
    return axios(
            {
            method:'POST',
            'url': 'https://127.0.0.1:5000/login/',
            data: {
                'username': username,
                'password':password,
            },
            mode: 'cors',
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            credentials: 'same-origin',
            'Access-Control-Allow-Origin':'*', // include, *same-origin, omit
            headers: {
                'Content-Type': 'application/json'
            },
        }
    ).then(response => {console.log(response)})
}

and ik this code works because it used to work before but i dont know what happened

this is my flask route that this is posting to

@auth.route('/login', methods=['POST', 'GET'])
def login_route():
    print('hello world')
    username = request.json.get("username", None)
    password = request.json.get("password", None)
    print(f'username:{username} password:{password}')
    data = jsonify(request.json)
    data.headers.add('Access-Control-Allow-Origin', '*')
    return f"<h1>{request.get_json()}</h1>"

$oRonny — Today at 12:00
this is the whole login.js
https://pastebin.com/drMxkTDe
i could really use some help
i think it some stupid error that i cant see, i dont know what i did for it to not work, it was posting data fine but i think i messed around with some tags and all of the sudden the function postLogin doesnt post data
the console says err:net somthing which is due to the flask server being https but without ssl cert
but it was https before

inland oak
#

Class based view is perfect for CRUD

#

first function for GET to READ object
POST to CREATE
PUT to UPDATE
DELETE TO DELETE

inland oak
swift wren
#

Cors is enabled in the python route

inland oak
#

Check in chrome devtools errors

#

in console and in network tab

#

it should be showing CORS errors

swift wren
#

I'm using flask brother I sent a code snippet of my route

inland oak
#

I already gave the answer. Your code shows me clearly the problem I mentioned

#

I had the same problem recently

#

with exception to using Axios to Django

swift wren
#

You sent a link for django cors

#

I'm using flask

inland oak
#

use flask cors then

swift wren
#

I am lol

inland oak
#

use chrome devtools to see the more detailed error then

swift wren
#

I have cors initialised in the create app function

inland oak
#

perhaps you did not initialized it in the right way

#

are you using reverse proxies, apache / nginx?

swift wren
#

Nah no proxies

#

I enabled https but I don't have any certs

inland oak
#

that can be a problem too

#

https without certs will give just the error of certs

#

read the error in chrome devtools. for your axios operation. check tabs console and network.

swift wren
#

bro im not a beginner

#

i've checked those tabs and the error which makes no sense persists

inland oak
#

show us the logs of devtools then

swift wren
#

it says err:network

inland oak
#

what says Network tab?

swift wren
#

i deactivated the component let me get it back up

inland oak
#

if it will work, then 99% problem is in the CORS

native tide
inland oak
#

if it will not work, then your http certs problems

swift wren
#

postman works