#web-development

2 messages · Page 174 of 1

versed python
#

django? use a filter on your queryset

dusk portal
#

yes

dusk portal
#

@arctic wraith ^^ ik u'll fix it , it's ezz for u pro

fiery stream
#

can we perform template inheritance from another app?

dense sleet
#

hello can someone help me with html?

thorn igloo
native tide
late creek
#

I just heard about it from a podcast it seems like a mix between Django and flask

#

so no experience sorry

mint hedge
#

no worries. i remember looking at it years ago. seems legit

versed python
native tide
#

Hey, my selenium keeps opening 'data;' Help please

naive blaze
#

Hello guys i need a help plz:
I use flask and I wonder if i can send a post request with js script to from a page loaded by route A to a route B ?

#

to be more cleare my page render in this route

#

and i want to send something like :

#

is it flask who block it, or its a mistake i did ?

royal musk
#

Could anyone help me? guys, help plz

thorn igloo
untold lava
#

use Order.objects.create or Order.create or just use entry.save() method.

dusk portal
#

done

dusk portal
#

im sure u have somewhere used

untold lava
#

or set up your urls and views?

dusk portal
dusk portal
naive blaze
royal musk
#

wait xD

untold lava
thorn igloo
untold lava
#

maybe it doesn't accept multiple methods?

royal musk
naive blaze
thorn igloo
#

can i see that route?

naive blaze
royal musk
naive blaze
#

it need to start with the same route

untold lava
thorn igloo
#

cause 405 means you're using a method that's not supported on that route

untold lava
naive blaze
thorn igloo
untold lava
#

idk js, so I can't help you @naive blaze

thorn igloo
#

are you making a request to this exact route?

untold lava
#

please before asking and waiting everything from us, just google guys

#

after if you couldn't solve, come to ask

#

I love stack ❤️

naive blaze
#

if i send to "Somthing-else/

#

it does not work

untold lava
royal musk
thorn igloo
#

you want to target a route by using a different route?

untold lava
naive blaze
untold lava
#

and what is your problem?

royal musk
untold lava
#

did you look the link I sent you?

#

hmmm okey, send your codes

#

did you follow all tutorial

naive blaze
untold lava
#

everything is necessery for that app.

royal musk
royal musk
#

polls/urls.py

from django.urls import path
from . import views

aap_name = "polls"

urlpatterns = [
    path("", views.index, name="index"),
    path("<int:question_id>/", views.detail, name="detail"),
    path("<int:question_id>/results/", views.results, name="results"),
    path("<int:question_id>/vote/", views.vote, name="vote"),
]
thorn igloo
royal musk
#

mysite/urls.py

from django.contrib import admin
from django.urls import include, path

app_name = "polls"
urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]
untold lava
#

there is a list on there called installed_app like...

royal musk
#

template/polls/detail.html

#
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>

<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
    <fieldset>
        <legend><h1>{{ question.question_text }}</legend></h1>
        {% if error_message %}<p><strong> {{ error_message }}</p></strong> {% endif %}
        {% for choice in question.choice_set.all %}
            <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{choice.id}}">
            <label for="choice{{ forloop.counter}}">{{ choice.choice_text }}</label><br>
        {% endfor %}
    </fieldset>
    <input type="submit" value="Vote ~CLICK~">
</form>
naive blaze
royal musk
untold lava
#

pastebin was banned on my country :/

royal musk
#

:/

#

wait

untold lava
#

nvm it, just delete all the processes you did on 4th tutorial

#

and redo again

royal musk
#

escape is not a result

#

xD

untold lava
#

idk, if it helps you but I cannot help you due to I am not on pc

untold lava
royal musk
#

:/

untold lava
#

idk, what's is the problem

royal musk
#

I will try solve this tomorrow, It's late.

royal musk
untold lava
#

yeah but what is causing this, idk it.

meager anchor
#

you probably want include('polls.urls', namespace='polls')

royal musk
#

i tried this

#

but django gave me an error that it is not supported

meager anchor
#

do you still ahve the error around?

#

if it's late, go to sleep! we'll be here tomorrow

royal musk
#

okay 🙂 thank you for every help,
bro. Goodnight!

next comet
next comet
# royal musk

also try leaving the action attribute empty, thus the form still should work, since when you leave it by default the action will be set to the current page

graceful flax
#

Hi

#

I've my project with django postgres and redis, it's a chat application

#

I'm looking to scale it, anyone with experience of where they've deployed it?

#

I've my test on heroku, I've been trying to deploy production to AWS beanstalk and failing at it. If anyone has any guide, would be helpful, the one's on Google are outdated and doesn't seem to work and AWS docs was really bad

meager anchor
#

if you want to learn a bit, then just getting a regular VPS (like digitalocean droplet, hetzner server, netcup vps) to deploy on is probably the best way to go. as for scaling it, it depends what your current bottleneck is, i would assume the first place to look would be the django app?

barren pagoda
#

is there a tutorial on building APIs with django without DRF? everything seems to suggest DRF but i want a barebones look at it

meager anchor
#

that depends on what you want your API to do - the most basic API could just receive a request, decode it from json, lookup some data, and serialize & return that as json

#

then you’ll probably also want things such as token authorization, validation, etc.

#

for validation, you could use database constraints, …

barren pagoda
#

yeah i want to do all that

#

returning as json first of all

#

since that is not clear from the tutorials

meager anchor
native tide
#

btw quick question, what are the default names for html, cs, and js files? On the mdn docs I saw index.html, main.css and javascript.js

cinder sequoia
#

Heyy can anyone please help me re-create a cool looking eportfolio?

calm plume
#

Only index.html for HTML

#

And in nodejs, index.js is the most common entry point but that doesn't matter in the browser

native tide
#

Well I want to use seperate files for css and js

calm plume
#

But it's not a bad idea to go with index.js

calm plume
#

Why does the name matter to that?

native tide
#

so index.js and what do I call my css file?

native tide
calm plume
native tide
#

I've also seen script.js an style.css are those common names?

native tide
calm plume
#

Some call in main.css, some styles.css, others globals.css, all are fine

calm plume
native tide
#

oh so what I have rn is index.html, main.css and javascript.js is all good?

calm plume
#

Yeah, that's fine

#

Although I've never seen javascript.js before

native tide
calm plume
native tide
native tide
calm plume
#

Basically, you can name anything besides index.html whatever you want

native tide
#

Is there a reason for that? I've seen main.html one time

calm plume
#

index.html is the commonly accepted entrypoint. Most services will always view that as the base of your project. (e.g. the url would be example.com instead of example.com/otherstuff)

native tide
native tide
#

thank you

#

Oh yeah and another thing

calm plume
#

I don't know if there's reasoning behind naming it index.html, but that's what it is 🤷‍♂️

native tide
#

Is this formatting good?

#

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>test</title> 

        <!--Link to css file-->
        
        <link href="style.css" rel="stylesheet"/>

        <!--Link to javascript file-->

        <script src="script.js"></script>

#

Or are spaces bad

#

and comments no good for html

calm plume
#

That looks fine, but you probably don't need a space between the comment and the actual line

calm plume
#

The fact that you're importing a css file and a js file can be easily understood by glancing at the code

#

You don't need to specifically say that

native tide
#

Right makes sense I've just started html/css not too long ago so I usually like to comment so I don't forget

#

are the links suppose to be under the title or nah?

calm plume
#

There are all sorts of guides on the order, but no official guidelines or anything that really matter

native tide
#

so there's no documentation for formatting?

calm plume
#

I mean, not really

#

What would there be?

native tide
#

Idk, html looks hard to read when all the code is clumped together

calm plume
#

There's no official style guides afaik if that's what you mean

calm plume
#

I prefer pug because of that actually

native tide
#

Is that a markup language or smt

calm plume
#

Basically an alternative syntax for html

native tide
#

oh that's cool. good to know

inland oak
#

oh, you alredy renamed, nvm

rustic sky
#

if anyone here knows how to use pythonanywhere, I'm going to need some help

#

I'm seeing YouTube videos showing using GitHub and cloning their website, but is there a way to have a private repo for that?

#

I was going to upload a ZIP file

native tide
#

Anyone familiar with Facebook Messenger Platform API?

native tide
inland oak
native tide
#

Oh kk thanks for the tip 👍

#
{
  "object":"page",
  "entry":[
    {
      "id":"<PAGE_ID>",
      "time":1458692752478,
      "messaging":[
        {
          "sender":{
            "id":"<PSID>"
          },
          "recipient":{
            "id":"<PAGE_ID>"
          },

          ...
        }
      ]
    }
  ]
}

Event Format
`
All webhook events have a common structure that includes information you will need to process and respond to the event, including the PSID of the sender and recipient of the event. In addition to the properties shown below, each event also has its own event-specific properties.

Note that entry is an array and may contain multiple objects, so ensure your code iterates over it to process all events. For a complete description of event properties, see Webhooks Reference.
`

It says here "Note that entry is an array and may contain multiple objects, so ensure your code iterates over it to process all events."

Anyone familiar with the Facebook Messenger Platform API? I wonder in what instance are there multiple events being delivered to a webhook?

lime mist
#
import socketio
from src.server_state import ServerState
from src.logs_handler import log, INFO, ERROR

sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins="*")
app = socketio.ASGIApp(sio)
server_state = ServerState()


# Default Events
@sio.event
async def connect(sid, environ):
    server_state.workers_online += 1
    server_state.add_worker(sid)
    server_state.rebalance_jobs()

    log(INFO, f"{sid} Connected!")
    log(INFO, f"Total online workers: {server_state.workers_online}")
    log(INFO, [(x.worker_sid, x.jobs) for x in server_state.worker_job_maps])

    await sio.emit("sid", sid, to=sid)


@sio.event
async def disconnect(sid):
    server_state.workers_online -= 1
    server_state.remove_worker(sid)

    log(INFO, f"{sid} Disconnected!")
    log(INFO, f"Total online workers: {server_state.workers_online}")
    log(INFO, [(x.worker_sid, x.jobs) for x in server_state.worker_job_maps])


@sio.event
async def get_job(sid):
    pass


@sio.event
async def get_account(sid, primary_job_id):
    pass
``` As you can see I'm using an `ASYNC socket.io` server. I wanted to ask whether I am required to spin a thread to resolve the request on ASYNC socket.io because some requests might take some time (1s - 3s) to resolve and I don't wanna interrupt other requests that might happen while solving this request
#

Example: On connection my server needs to rebalance jobs for all the connected workers and it might take some time

#

I'm running the server using uvicorn like so: uvicorn server:app

versed python
lilac heart
#

should i use fastapi or django as backend? planning to use it with both react and react native and mysql as db

#

i asked this over at #software-architecture yesterday and was told to use fastapi instead, not sure if thats better or worse:

so im creating a project with django as backend and react as frontend, should i:
a) use django-admin startproject then create an app called frontend and manually add all the required stuff for react (since idk still how to npx create-react-app in a django app, it just doesnt work for me fsr)
b) use django-admin startproject then without creating an app, do npx create-react-app then somehow link django to it? im not sure how that would work
c) use npx create-react-app then somehow create a django project inside, not sure how that would work either

any help would be appreciated!

dusk portal
#
class Order(models.Model):
    name=models.CharField(max_length=50)
    email=models.EmailField()
    author=models.OneToOneField(User,on_delete=models.CASCADE,unique=False)
    phone_no=models.IntegerField(default=0)
    address=models.CharField(max_length=100)
    zipcode=models.IntegerField(default=0)

    def __str__(self):
        return  self.name```  so when i'm out the form  from user for example admin
thorn igloo
lilac heart
#

wdym?

#

ive followed some tutorials that uses django and react combinations and it works pretty well

thorn igloo
#

you know how django uses template rendering etc, that stuff is irrelevant when you use something like react. i don't know if i'm making sense here

lilac heart
#

ah i see what u mean

#

yea its kinda counter intuitive in a sense

#

but i thought some big companies like instagram uses django and react

thorn igloo
#

i mean you can use it but you'll be using django like an api mostly

lilac heart
#

i see

thorn igloo
#

same for any other backend framework really

lilac heart
#

yea i get it now

#

guess itd be the most intuitive if i just go and use fastapi

dusk portal
#
class Order(models.Model):
    name=models.CharField(max_length=50)
    email=models.EmailField()
    author=models.OneToOneField(User,on_delete=models.CASCADE,unique=False)
    phone_no=models.IntegerField(default=0)
    address=models.CharField(max_length=100)
    zipcode=models.IntegerField(default=0)

    def __str__(self):
        return  self.name``` ```py
@login_required
def order(request):
    if request.method=='POST':
        name=request.POST.get('name')
        email=request.POST.get('email')
        author=request.user
        phone_no=request.POST.get('phone_no')
        address=request.POST.get('address')
        zipcode=request.POST.get('zipcode')
        print(author)
        entry1=Order(name=name,email=email,author=author,phone_no=phone_no,address=address,zipcode=zipcode)
        entry1.save()
        return HttpResponseRedirect('/')
    return render(request,'index/order.html')``` so the problem here is the 1st time when i  filled the form when logged in from account called "admin" it works then i again tried to fill same form when logged in with user called "admin" it throws error , then i filled form with user  "test" it works hence it shows user can fill form only 1 time how can i fix that error ```IntegrityError at /order/
UNIQUE constraint failed: index_order.author_id
inland oak
#

django rest framework as backend services fine to react

lilac heart
#

trying to build something like a twitter/instagram clone

inland oak
#

instagram was built with django 😉

lilac heart
#

yea-

#

but thought its more intuitive if its fastapi

inland oak
#

the only issue with django you will have

#

partially limited async support

#

it works for views, and there are django channels for web sockets, that's ok mostly

lilac heart
#

yea thats the thing i found on google

inland oak
#

but Django ORM is sync at the moment

#

that's why Fast API can be preffered

#

since it has no in built ORM in it

#

you can setup from the start async friendly ORM

lilac heart
#

and django is slower compare to fastapi too

#

idk i think i might give fastapi a try

inland oak
#

there are so many ways to speed up web app

lilac heart
#

tahts true

inland oak
#

that at the end it will probably no matter which framework you used at the start

lilac heart
#

yea

#

i see

inland oak
#

the good things about django, that it brings really fast development at least

#

any feature is just plug and play

#

so it could make better end result just because you will have more time to use for development of architecture and optimization

lilac heart
#

ah

#

i mean, ig i could always try one out and if it doesnt fit i can just switch

inland oak
#

i hope they will eliminate their last weakness with ORM not async supported though

#

we can expect it around december to see perhaps

lilac heart
#

oooo

inland oak
#

it is scheduled for Django 4.0

lilac heart
#

damn

#

then itd be pretty perfect

inland oak
#

yeah

twin shore
#

so im extremely new to web designing as in ive pretty much never done it but im trying to find if theres a way to read mouse coordinates through something like flask or django. I normally use tkinter which has the ability to track mouse coordinates, but I was considering trying a website but im struggling to find ways to track mouse movement. does anyone know a way to do this? if someone responds please @ me 🙂

thorn igloo
twin shore
thorn igloo
#

you're just using javascript to read the mouse co-ordinates, and sending them to the backend if that's what you want too do

twin shore
#

alright sounds good ill definitely look into that thanks

rustic sky
#

Is there a way to see something like this in VSCode?

#

project isn't uploaded to GitHub but I am curious

next comet
#

it gives you the time you spend on a certain project, also shows the IDE, languages, OS that you have used

#

look it up

rustic sky
#

even better

#

now I wish I had that long ago

rustic sky
#

as in... not recording... but just how the project is as it stands

#

wait a minute...

#

is this it?

#

no, nevermind

next comet
#

at the bottom there are projects section

#

and when you click on some project it shous you some statistics

#

but im not sure if its the time spend on that certain project and language or what languages portion are in the project

rustic sky
#

But that is also something I’ve wondered about so I am keeping this plug-in

native tide
indigo vessel
#

hey can i ask a question

#

my concern is that my css peak even if its enabled, it won't let me peak from html to css

#

and vice versa

#

hello is anybody around?

mint folio
#

So user can only have one order with this unique constraint

indigo vessel
#

tried to restart the vscode

#

tried uninstall and reinstall and nothing happens

barren pagoda
#

i have a relatively simple (i think) issue that i'm not sure how to solve with django regarding models and subclassing a model

i have a Payment class (inheriting from models.Model) and i want to extend this into more subclasses, because each Payment has a payment_method type which is a string like 'creditcard', 'paypal', etc..

so i have created a CreditCard class which inherits from Payment and has fields like name, number, cvv and so on. and another PayPal class which has fields like email and so on.

what i want to achieve is something where, when someone is creating a new payment, when they specify the payment_method string, they also have to add the corresponding extra fields specific to that payment method -- e.g. they would have to include the number of the credit card if they choose 'credticard'

how do i go about this?

next comet
#

guys Is there any way i can clean a specific common field between let say 3-4 forms and to write a Mixin for it? and if so how can i do it

#

instead of copy pasting the same stuff in all forms

untold lava
#

to look details search: Django ForeignField

barren pagoda
#

thank you! i'll look for that

untold lava
#

Follow the tutorial of django there is an example in there.

mint folio
#

But is your question about how to collect the different info for different payment methods?

barren pagoda
#

i want something like when i hit /api/payments itll show me every payment and generic information (common to all) and then when i hit /api/payments/<id> itll show me all that payment's data including its specific parameters like number if it's a credit card

mint folio
#

Well in my example ID is needed as it the transaction tables makes reference to it from payable id.

barren pagoda
#

because i want one /api/payments endpoint with a POST on it where i'm expecting the given parameters depending on the payment_method the body has

mint folio
untold lava
mint folio
#

For your payment data collection just have some logic that show le the appropriate view for each payment method. For example, for card payment you will show the credit card form, and for PayPal you will redirect to PayPal

untold lava
#

I think you shouldn't create submodels which inherits base Payments model and just define payment_method string with data getting from a form page.

mint folio
#

Also for this certain design patterns can make this easy, and more maintainable so in the future it’s easier to add or remove payment methods without affecting other paths of the code.

native tide
#
{
  "object": "page",
  "entry": [
    {
      "id": "<PAGE_ID>",
      "time": 1458692752478,
      "messaging": [
        {
          "sender": {
            "id": "<PSID>"
          },
          "recipient": {
            "id": "<PAGE_ID>"
          },
          "timestamp": 1458692752478,
          "message": {
            "mid": "mid.1457764197618:41d102a3e1ae206a38",
            "text": "hello, world!",
            "quick_reply": {
              "payload": "<DEVELOPER_DEFINED_PAYLOAD>"
            }
          }
        }
      ]
    }
  ]
}

Here's a typical payload when a user sends a message (Facebook Messenger Paltform API).

My webhook receives this POST request however, let's say we've asked the user to provide some text input.

How would we generally setup something that:

  1. Catches that it's the same user in order to respond to the same user
  2. Wait for their text input
stone condor
#

How can I redirect to a external url with flask?

next comet
#

how can i add a field to all my forms and not do it by hand ? any ideas appreciated

dusk portal
mint folio
dusk portal
#

TypeError at /order/
Direct assignment to the forward side of a many-to-many set is prohibited. Use author.set() instead.```

glacial gazelle
#

Could somebody help me? "py manage.py runserver" returns line with text "python" and refuses to start server. What do I do?

glacial gazelle
opaque rivet
#

what's the error?

glacial gazelle
opaque rivet
#

send a screenshot

glacial gazelle
opaque rivet
#

are you in the root directory of your project when you run the command?
did you start the project with django-admin?

glacial gazelle
grave pine
#

Hi i am getting this error, anyone could help? ``/usr/local/bin/python3.9 /Users/vincentz/Documents/sre-rre/app/src/controller/init.py
Traceback (most recent call last):
File "/Users/vincentz/Documents/sre-rre/app/src/controller/init.py", line 2, in <module>
import pandas
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/init.py", line 11, in <module>
import(dependency)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/numpy/init.py", line 139, in <module>
vinfo = get_versions()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/numpy/_version.py", line 21, in get_versions
return json.loads(version_json)
AttributeError: module 'json' has no attribute 'loads'

Process finished with exit code 1``

untold lava
#

try to rename init.py to __init__.py

#

@grave pine

grave pine
#

yes, my current folder name is

grave pine
untold lava
#

I couldn't understand why numpy couldn't find json's loads method idk I think maybe it was installed wrong somehow :/

grave pine
#

haah, i searched on stackoverflow people has the same issue, all changed file name then its fine, but in my case, my file name is fine, so i don;t know what else to do

native tide
untold lava
#

open your command prompt and type python to switch python shell

#

then type these line-by-line

#
> import json
> json.loads({'test': 'testing this method whether exists or not'})
#

check your python path

#
import sys
print(sys.path)
#

because there is something wrong in your modules path

#

like /Library/Frameworks/Python.framework, it should have been like python/Lib/site-packages/... but not...

#

if you change your packages path you should set this folder's path to your PATH or PYTHONPATH environments.

#

@grave pine

random jolt
#

Help please

I've heard that socket in used in creating a chat app, so if you are a python backend programmer and you're told to make one(an API that does that) to send to the front-end, how do one go about it?

chrome reef
#

quick help
extra_kwargs = {"email": {"required": False}}
how do I write if I have an additional field "speciality" that I also want to set to false?

elder pier
#

Channels takes away the need to figure out a bunch of socket stuff as well as Django’s auth and session system

#

It’s pretty cool

#

But if you really want to learn how to use the WebSocket API then I believe Mozilla has a few articles that might interest you

wet mortar
#

the admin page of my site is missing CSS . I've deployed it on pythonanywhere using django framework . Anyone who can help with the same

meager anchor
#

@wet mortar check the network analysis tab of your browser, do you get 404 for the static pages? does pythonanywhere host the static files?

wet mortar
#

and 404 error is there

meager anchor
#

I think this document is what you're looking for

jade lark
wet mortar
#

i have them hosted

jade lark
#

I am aware.

#

You can open a console. Activate the virtualenv (if using one) and run that command.

wet mortar
#

specified as well

jade lark
#

Just have it set to static

#

not static/admin

dusk portal
#

ohk so

wet mortar
#

lemme change

dusk portal
#

plz help me

wet mortar
#

also ^

dusk portal
#

see terminal

#

why this on a2.author

wet mortar
dusk portal
#
class Order(models.Model):
    name=models.CharField(max_length=50)
    email=models.EmailField()
    author=models.ManyToManyField(User)
    phone_no=models.IntegerField(default=0)
    address=models.CharField(max_length=100)
    zipcode=models.IntegerField(default=0)

    def __str__(self):
        return  self.name```
wet mortar
dusk portal
#
TypeError at /order/
Direct assignment to the forward side of a many-to-many set is prohibited. Use author.set() instead.
``` this error tooo
jade lark
#

@wet mortar including the directory?

jade lark
wet mortar
dusk portal
jade lark
jade lark
# dusk portal what u mean

Literally exactly that. Best bet if you're uncertain is to refer the documentation for Django. EX: Many to one, M2M etc

jade lark
# wet mortar

Try this

STATIC_ROOT = os.path.join(BASE_DIR, 
"static")
wet mortar
jade lark
wet mortar
#

but

dusk portal
#

first import os then Path(BASE_DIR , "static")

dusk portal
#

im sure it will work

#

seee

#

and yes import os

jade lark
dusk portal
#

and paste

#

urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)

jade lark
#

No

#

Do not do that

dusk portal
#

;-;

jade lark
#

configuration should stay in your settings file/package. You don't want it scattered.

#

Single source of truth

wet mortar
jade lark
wet mortar
#

also

#

my bad

#

i was doing /home/parvashah/.virtualenvs/myproj/lib/python3.8/dist-packages/django/contrib/admin/static/admin instead of /home/parvashah/.virtualenvs/myproj/lib/python3.8/site-packages/django/contrib/admin/static/admin

jade lark
#

Nadda. The path was incorrect

#

yeah 😛

wet mortar
#

two fucking hoursssss

#

i am so pissed

#

i should just doze off

jade lark
#

It happens man. One time I lost almost 4 hours over a comma.

wet mortar
wet mortar
#

where you from ?

jade lark
#

Canada

#

You?

wet mortar
#

india :/

wet mortar
dusk portal
#

btw

jade lark
#

Show us your views lol

dusk portal
#

my views:

wet mortar
#

views bro

#

told ya

dusk portal
#

oh

wet mortar
#

what do you do ?

dusk portal
#
@login_required
def order(request):
    if request.method=='POST':
        name=request.POST.get('name')
        email=request.POST.get('email')
        author=request.user
        phone_no=request.POST.get('phone_no')
        address=request.POST.get('address')
        zipcode=request.POST.get('zipcode')
        print(author)
        entry1=Order(name=name,email=email,author=author,phone_no=phone_no,address=address,zipcode=zipcode)
        entry1.save()
        return HttpResponseRedirect('/')
    return render(request,'index/order.html')```
jade lark
#

What are you doing on the template?

dusk portal
#

it's for ecommerce site and i used author here so every user can see thier order history before a day i was doing from OneToOneField so it was working but was not taking more then 1product from same user

#

so i got to know about this field

#

Manytomany

wet mortar
mint folio
#

Many to many would be wrong for that case

#

A user has many orders

dusk portal
#

so Manyonmany should work ig

mint folio
#

Many to many would be if an order can belong to multiple users

eternal blade
jade lark
#

there is nothing wrong with using a many to many here. It depends on how he wants to represent the relationships.

#

for example he would use a onetomany

dusk portal
#

ohh

jade lark
#

and then use object_set but that depends on the use case

dusk portal
#

what should i use here how u guyz indentify what to use when and where

#

wow

eternal blade
#

You will be using ManyToManyField when creating a custom user profile etc...

dusk portal
#

ohh

#

wait lemme do that

mint folio
eternal blade
dusk portal
#

when to use Manytomany when to use onetomany when to use foreignkey

#

damn

jade lark
#

To build upon that if you want all orders for a user (to render in a template or view) you would then use ```
orders = User.order_set.all()

dusk portal
#

i have idea of OnetoOne

eternal blade
#

ManyToManyField will be using in creating a like button etc...

jade lark
#

Using a foreign key as stated above is a OneToMany

mint folio
mint folio
#

Then not sure why you ask again

dusk portal
#

cez

#

it's 1:37 am

#

and my mind says

#

u r noob

mint folio
#

@dusk portal You should consider looking at e-commerce systems and how they work and are structured. They can get complex and so if you are stuck on something simple like this then you will face more issues later

dusk portal
#

ohh

#

i have made many apps but

#

blog and some

#

but this is kinda very very complex

mint folio
#

Well yeah if you don’t plan or think it through properly you’ll end up in a mess

dusk portal
#

yes i just make features, later change and make stuff confusing

#

i dont plan

floral flicker
#

Can someone explain to me how domains work? How do people claim them and how do all of those websites that sell domains get them?

random jolt
floral flicker
#

And where did the people who have the domain get it from?

next comet
#

do you use plugins for django guys?

#

if you write it on vs code

random jolt
random jolt
edgy anvil
#

wait guys im new to flask so im not sure on what things i need to learn in order to make like a loging and signup page on flask

alpine ingot
edgy anvil
alpine ingot
edgy anvil
olive tiger
uneven wren
#

Hi this is more related to javascript and html than python so am sorry, but i need a help..
Im trying to store json in html data attribute then take it out edit that and save again, but i have problem with encoding all the time my "x":false will always be saved as "x":"false".
Can someone tell me how to encode it ?

raw compass
uneven wren
#

well i know about parse and am parsing it, but prbbly in the wrong way cuz it always get "false" on resaving it

raw compass
uneven wren
#

Well do i need to stringify object when i want to save him in html data element using element.attr("data-x",val) ?

edgy anvil
olive tiger
#

the db you need to create manually, models will be used to create the schema in the db

olive tiger
#

when you run makemigrations or how it is called in flask

edgy anvil
#

so i just make a new file for users say called users.db ?

olive tiger
#

it is not straight, check the flask docs about this

olive tiger
#

check the flask docs about this

edgy anvil
#

okk

crimson canyon
next comet
#

Morning ppl, I wanna ask something about validators. I have an ImageField, and I'm wondering is it enough the built in validator in the actual ImageField, or should I use the django- validate_image_file_extension

next comet
#

also what do you consider a good max image file size (like 1 MB 2mb ?)

native tide
next comet
#

i guess the more resolution more pixels and higher file size ?

#

Im building a photo uploading site, and Im wondering is there any good reason to have different image file size validations for the normal image and a profile image (since profile image are just small pictures)

noble bolt
#

Hello guys, can someone tell me what I'm missing!
I start using django_restframework, I wrote a simple serializer to get started, when I start the shell and try to import the file I get this error

>>> from myapp.serializers import NotesSerializer
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/omer358/PycharmProjects/NotesApp/Notes/myapp/serializers.py", line 2, in <module>
    from Notes.myapp.models import Notes
ModuleNotFoundError: No module named 'Notes.myapp'
>>> 

when I tried to import my model it worked just fine!

#

this the structure of my project:

(NotesApp) omer358@OMO:~/PycharmProjects/NotesApp$ tree
.
├── main.py
├── Notes
│   ├── db.sqlite3
│   ├── manage.py
│   ├── myapp
│   │   ├── admin.py
│   │   ├── apps.py
│   │   ├── __init__.py
│   │   ├── migrations
│   │   │   ├── 0001_initial.py
│   │   │   ├── 0002_rename_last_modified_notes_last_modify.py
│   │   │   ├── 0003_rename_last_modify_notes_last_modified.py
│   │   │   ├── 0004_rename_last_modified_notes_modified_at.py
│   │   │   ├── __init__.py
│   │   │   └── __pycache__
│   │   │       ├── 0001_initial.cpython-39.pyc
│   │   │       ├── 0002_rename_last_modified_notes_last_modify.cpython-39.pyc
│   │   │       ├── 0003_rename_last_modify_notes_last_modified.cpython-39.pyc
│   │   │       ├── 0004_rename_last_modified_notes_modified_at.cpython-39.pyc
│   │   │       └── __init__.cpython-39.pyc
│   │   ├── models.py
│   │   ├── __pycache__
│   │   │   ├── admin.cpython-39.pyc
│   │   │   ├── apps.cpython-39.pyc
│   │   │   ├── __init__.cpython-39.pyc
│   │   │   ├── models.cpython-39.pyc
│   │   │   ├── serializers.cpython-39.pyc
│   │   │   ├── urls.cpython-39.pyc
│   │   │   └── views.cpython-39.pyc
│   │   ├── serializers.py
│   │   ├── templates
│   │   │   └── myapp
│   │   │       ├── detail.html
│   │   │       └── index.html
│   │   ├── tests
│   │   │   ├── __init__.py
│   │   │   ├── __pycache__
│   │   │   │   ├── __init__.cpython-39.pyc
│   │   │   │   └── test_models.cpython-39.pyc
│   │   │   └── test_models.py
│   │   ├── urls.py
│   │   └── views.py
│   └── Notes
│       ├── asgi.py
│       ├── __init__.py
│       ├── __pycache__
│       │   ├── __init__.cpython-39.pyc
│       │   ├── settings.cpython-39.pyc
│       │   ├── urls.cpython-39.pyc
│       │   └── wsgi.cpython-39.pyc
│       ├── settings.py
│       ├── urls.py
│       └── wsgi.py
└── README.md

next comet
#

how can i hit breakpoint in post_delete signal, no matter what i do, the ide just doesn't go to the signal

meager anchor
#

Notes in this case is the (django) project with asgi.py etc.

meager anchor
meager anchor
next comet
rigid loom
#

@glacial perch hello! I'm afraid we don't allow advertisement of non-python projects here.

meager anchor
next comet
#

in the IDE

#

im using vscode and just put the red dot on the signal

#

i tried to put it on the view where the .delete() is called but it just continues ahead and doesn't jump to the file where my signal is

#
@login_required
def profile_details(request):
    profile = Profile.objects.get(user_id=request.user.id)
    profile.full_name = profile.first_name + ' '+ profile.last_name
    user_images = request.user.photo_set.count()
    user_comments = request.user.comment_set.count()
    user_liked = request.user.commentlike_set.count()

    recent_photos = request.user.photo_set.all().order_by('-posted_at')[:4]
    if request.method == 'POST':
        form = ProfileForm(request.POST, request.FILES, instance=profile)
        delete_image_form = DeleteProfileImageForm(request.POST)
        if form.is_valid() and delete_image_form.is_valid():
            profile = form.save(commit=False)

            if delete_image_form.cleaned_data['delete_image'] == 'True':
                profile.image.delete()
            else:
                profile.save()
            return redirect('profile')
    else:
        form = ProfileForm(instance=profile)
        delete_image_form = DeleteProfileImageForm()

    context = {
        'form': form,
        'delete_image_form': delete_image_form,
        'profile': profile,
        'user_images': user_images,
        'user_comments': user_comments,
        'user_liked': user_liked,
        'recent_photos': recent_photos,
    }

    return render(request, 'profile/profile.html', context)
#

this is my view and i tried to put it on the line where is profile.image.delete()

#
@receiver(post_delete, sender=Profile)
def delete_profile_image_media(sender, instance, **kwargs):
    """Removes media files when profile image is deleted."""
    if instance.image:
        default_storage.delete(instance.image)```
#

and this is my signal

heady ore
#

try manually connecting instead of using @receiver

#

I had a quick DRF question of my own.

class Resource(models.Model):
    uri = models.URLField(primary_key=True)

class ResourceSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Resource
        fields = ('uri',)

class ResourceViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = models.Resource.objects.all()
    serializer_class = serializers.ResourceSerializer

router = DefaultRouter()
router.register('resource', views.ResourceViewSet)
....

See above for a sample view, model, serializer and router config.

Imagine you have a resource like Resource(uri="https:/example.com/foo.bar")

How would I view its details.?
/api/resource/[what goes here]

Normally a primary key goes there. But since my PK itself is a URL how does it work?

I have for example tried something like /api/resource/https%3A%2F%2Fwww.example.org%2Ffiles%2F9999%2F9999.zip with no success

#

These are the RE printed by the DEBUG config

api/ ^resource\.(?P<format>[a-z0-9]+)/?$ [name='resource-list']
api/ ^resource/(?P<pk>[^/.]+)/$ [name='resource-detail']

I have tried encoding . with %2E with no success as well.

olive tiger
#

your resource still has an id

#

because the model creates a table with id and url columns

#

you can also specify url instead of pk in your urls or use lookup_field to change that behaviour

#

but I would not do it

heady ore
#

There is no id column in my APP_NAME_Resource table

#

I just checked.

#

That is due to primary_key=True i assume.

olive tiger
#

just call any record from the db and check its id

#

I do not know what you are using for this, but there is an id field

#

id column is created by default

#

oh, primary key - yes

#

that is correct

#

I have not noticed it

#

why do you do it?

heady ore
#

it makes sense to me URI is unique.

olive tiger
#

just use the default, do not overcomplicate things

#

just make it unique

#

unique=True

heady ore
#

sure i can not make uri primary. But what is the solution for this? Are string primary keys just not possible in DRF

#

i don't know what i'm doing wrong, since other string primary keys work fine.

olive tiger
#

maybe possible but what is the point for that?

heady ore
#

just URI's don't work.

olive tiger
#

uri's have some special characters, which may break something

#

I would not do it any way

heady ore
#

well there's no explicit point. String PKs are usually equally fast as integer PKs and in this case i wouldn't have to make a separate column and users could identify the resource with the URI

#

why have id and a URI?

olive tiger
#

also it will significantly decrease the performance

olive tiger
#

imagine how your urls will look https://my-domain.com/https://sfghskjhg/sdlfsldkfj?slkdjf=lskdjflsj

#

😆

heady ore
#

but that makes sense no?
I have viewing a detail for that particular URI.
So to me it is much better than https://my-domain.com/some_opaque_id
There is virtually no performance difference between integer and string primary keys for my use case.

olive tiger
#

the slashes brake it

#

I would not do it any way

bright grove
#

hi, is it right place ask for help regarding selenium I am having difficulty while running it

olive tiger
#

there are also help channels, which you can use

bright grove
olive tiger
#

if you use selenium with python - also fine

#

but I am not local, so no binding here 😆

bright grove
#

let me try asking

elder nebula
#

What's the most practical way in django to check if data matches data in database. I've been using

try:
    if Model.objects.get(date__iso_week_day=selected_weekday):
      # Logic
except: ObjectDoesNotExist:
    # Logic```
#

is that the most effective & practical way?

glacial perch
olive tiger
elder nebula
#

ohhh

#

thx

olive tiger
#

actually, with if also works

elder nebula
#

yeah, I've been using the if in my projects. Don't know if it's bad

olive tiger
#

filter looks cleaner to me

elder nebula
#

get gets you the item, filter just filters the queryset I think

#

suitable for my case

olive tiger
#

yes, but you do not need those constructions with try-except

elder nebula
#

true

olive tiger
#

also for get you need to check for multiple values: try: except: except: becomes bigger

elder nebula
#

yes, otherwise error occurs

#

but if you make the field unique, you don't

olive tiger
#

depends on your search criteria

elder nebula
#

true

olive tiger
#

but, yes, searching on a unique filed should work

elder nebula
#

It's true that the try gets bigger and that's where need to start thinking other options

olive tiger
#

I know, some people overwrite the default get, with including the try except

#

but filter looks simpler solution

#

and get anyway uses filter 😉

elder nebula
#

it does?

olive tiger
#

yes, you can check the source

#

so, get looks somewhat redundant

elder nebula
#

it returns result_cache

#

ohh it uses filter but on it self

olive tiger
#

but it uses filter to get the value, if I am not mistaken

elder nebula
#

clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)

#

so filter is as fast as get?

#

because if application needs to check 1000s of records, it needs to be fast

olive tiger
#

I was never interested in knowing it

elder nebula
#

Would be cool to discuss it with someone who has had app with large amount of records / production

olive tiger
#

probably, the difference is not that big

elder nebula
#

yeah

olive tiger
#

also try-except adds up to the time

elder nebula
#

The most important thing is that the time stays relatively close to same

olive tiger
#

looks the same to me

elder nebula
#

yeah, if it doesn't take seconds to get the data to the page, it's fine

olive tiger
#

in my experience those large apis had much bigger problems with performance than comparing get and filter 😆

elder nebula
#

I might do a test app which I load with lots of database records and test different methods

elder nebula
olive tiger
#

yes

elder nebula
#

get only gets one

#

it was nice discussing with you

olive tiger
native tide
#

A bit of newbie here to web development , but would flask be a good starting point to start learning web dev?

olive tiger
#

personally, I find django better for this

native tide
#

what benefits do you think django has over flask ?

supple bramble
#

Django is much larger than flask and has a amazing orm, it provides really useful things like User model, Admin site, Authentication system, Security etc. Django is better suited for large scaled application while Flask is great for smaller projects, now you may ask why not use django for smaller projects? Well you surely can but that would be way too complicated, with flask you can create a simple API with like 5 lines, with django you would need settings.py, urls.py, asgi.py, wsgi.py, your actual app and stuff which is too overkill for a smaller project

#

Imo it really depends on what you wanna do, neither Django or Flask are too hard atleast to start with. Personally I would say django because i'm a bit biased towards it 😅

native tide
#

Thanks for that , great information . But for someone who is a complete beginner (I have no projects set at the moment) , would you still recommend me learning django

#

in future I would want do larger projects , so I guess im answering my own question . Go for django

supple bramble
#

yeah, in case it gets confusing then you can try flask

#

Corey Schafer on YouTube has a really great Django series (he also has a great Flask series), highly recommend it. Other than that, Django documentation is also very well written

native tide
#

Didnt know Corey the goat had a series on Django , that sounds super

supple bramble
#

haha yeah

native tide
#

just want to play devils advocate here but doesnt netflix and reddit use flask ? maybe im not understanding your point , but you can still use flask for larger projects its just harder ?

meager anchor
#

nothing stops you from using flask on a larger project, or django on a smaller, but I agree with @supple bramble that django eases working on big applications very very much. i think at the scale of netflix / reddit you can just throw your 500 developer team on it and it doesn't really matter much which framework they're using

native tide
#

yeah thats fair , thanks

heady ore
#

SlugRelatedField but for multiple slug_fields instead of one in Django DRF?

heady ore
#

Okay so there is none. I just created a new serializer i guess

gritty cloud
#

as volcyy said, it eases large projects by a lot

spark igloo
#

Guyzz Please help me with This ASAP

#

anyone There ?

#

Plzzzz

jovial cloud
spark igloo
#

So i Downloaded Django

#

and in that Tutorial

#

The Person runs

#

django-admin in terminal

#

but it isnt working in me

random ginkgo
#

you should install django with python command in terminal

spark igloo
spark igloo
random ginkgo
#

enter django-admin --version (now)

random ginkgo
spark igloo
#

Thanks For ur Time but Didnt Work

jovial cloud
spark igloo
#

Will Check'

#

it

eternal blade
#

Install django in a python virtual environment

spark igloo
#

Yea Worked

#

Thanks

#

Everyone

lament temple
#

if i run debugger does it fix my code for me

#

'

eternal blade
#

The debugger helps you to debug the code.

#

It doesn't automatically fix it

jovial cloud
#

Use src="{{url_for('static', filename='1.jpg')}}"

olive tiger
# native tide what benefits do you think django has over flask ?

personally, I think, the django's complexity is its strong point, also for a beginner. Flask is built in such a way, that it only has a small number of functionalities and you need to search and integrate into your project the ones, which are missing, i.e. almost everyhting. Then you may have some trouble to make them all working together. Django has the most of the things included and setup. So you just start a project with 2 commands and it has all the things you need already structured for you in a convenient way (there was a comment about creating all those, but they are created for you automagically). i see more advantages than disadvantages - all the components are there, you learn to properly structure your project, you learn about the flow request-response, easy db integration, great orm, authn/authz, pagination, serialisation via DRF etc. etc.

eternal blade
#

Yeah

#

The main problem with Django is it's complexity for beginners

#

If you are not that familiar with python even the official Django tutorial can get a little confusing

toxic flame
#

true

hardy nebula
#

My question might be silly, I have a doubt

What's use of learning HTML when website hosting and making sites are there and we can design the website through wordpress. I know HTML but still don't know how I implement it to make one website. Someone please answer..

eternal blade
#

Making web sites using HTML, CSS and JavaScript give more control over what you are building

native tide
#

When I send a post request to my Django API

#

I get a Bad Request error xhr.js:177 POST http://localhost:8000/api/create-post/ 400 (Bad Request)

#

this is the view in my django api ```py

class CreatePost(generics.CreateAPIView):
permission_classes = [permissions.IsAuthenticated]
serializer_class = PostSerializer
queryset = Post.objects.all()```

#

this is the urls ```py
urlpatterns = [
path('search/', PostListDetailfilter.as_view(), name='postsearch'),
path('', PostList.as_view(), name='listcreate'),
path('posts/str:slug/', PostDetail.as_view(), name='detailcreate'),

path('create-post/', CreatePost.as_view(), name='createpost')

]

#

and this is the function in my react component ```jsx

afterSubmit = () => {
console.log(this.state.data);

axiosInstance
  .post(apiURL + "create-post/", {
    title: this.state.data.title,
    author: this.props.users.filter(
      (user) => user.username == localStorage.getItem("currentUser")
    )[0].id,
    excerpt: this.state.data.excerpt,
    content: this.state.data.content,
  })
  .then((res) => {
    this.props.history.replace("/");
    console.log("foo");
  });

};``` This is the method that runs when I click the submit button.

scarlet kiln
#

I have a flask app which runs fine from pycharm but when I try to run it with the same venv from the command line, it can't find the stuff it's supposed to import

#

does anyone have any idea why that might be?

mystic wyvern
#

What the difference between nav and header in use case

calm plume
#

Header is specifically the top part of the page

mystic wyvern
#

How it can be in nav

calm plume
#

It just means navigation

scarlet kiln
#

quite the opposite navs can be in the footer

calm plume
#

for example on this website, the footer is a bunch of links to navigate to various pages

mystic wyvern
native tide
#

👀

#

Still struggling with the same problem

#

11 hours straight

calm plume
#

The nav tag can hold anything that's used for navigation

opaque rivet
native tide
#

I'll try that

#

That helped me out man!

#

I got to know from response.response.data that I wasn't specifying a slug field

edgy anvil
#

Hello, I am new to flask website development and i am running into an error.
When i try to execute the command db.create_all() its not creating the users.db file that it is supposed to

#

is there any fix to this?

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @tired siren until <t:1627171184:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 118 newlines in 10s).

edgy anvil
nocturne jetty
#

!unmute 535867884711444491

lavish prismBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @tired siren.

nocturne jetty
#

!paste @tired siren Use this.

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.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

tired siren
#

here it is

#

It is an AWS, django, nginx and gunicorn related question

raw imp
vestal hound
#

maybe you could elaborate

tired siren
#

What are you looking for?

edgy anvil
#

in flask when i do {{ form.username.label() }} i get this error

#

did they change this?

#

or am i missing something

#

nvm i fixed it i was missing a pair of parenthesis after i defined forms=Registerform

versed python
native tide
#

Hey

#

i wanna learn web developing

#

,_,

#

where do i start?

native tide
#
<form method="POST">
            <input type="text" name="test" id="button1">
            <button type="submit" class=test1>test</button>
            <button type="submit" name="random" value="random">test</button>
        </form>
#
.button1 {
    position: relative;
    bottom: 30;
}
#

isn't positioning the button

#

😦

opaque rivet
dusk portal
#

umm

opaque rivet
dusk portal
#

bro

#

i need some help

#

no wait first i will use my mind

native tide
versed python
opaque rivet
native tide
#

px

#

it still doesn't change position

opaque rivet
native tide
#

i did

#

ayo i need some advice

#

:c

#

what

#

i want to learn backend web developing

#

it it ok if i dont have much frontend knowledge?

#

so where do i start?

opaque rivet
# native tide

meaning your css file isn't being found, so your styles aren't being applied, possibly wrong path

native tide
#

i'll try pass in the path

opaque rivet
native tide
#

@opaque rivet still doesn't work

#

so i should learn django?

opaque rivet
native tide
#

yes

opaque rivet
native tide
#

hmm

#

ok thx

opaque rivet
#

hmm, in that case CTRL + F5 on your page to reset cache @native tide

#

and see if anything changes

native tide
#

still nothing

#

i've been trying for an hour now

#

not sure what the problem is

#

"not allowed to load local resource"

#

lol

opaque rivet
#

oh, just realized you're trying to reposition:

<input type="text" name="test" id="button1">

To access IDs you have to use #, thank @versed python for that

#button1 {
    position: relative;
    bottom: 30;
}
opaque rivet
# native tide

btw, this looks like the request to submit your form, not the request to retrieve the .css file.

native tide
#

oh...

#

this is without the path

#

when i pass in path it says unable to retrieve local resource

scarlet kiln
#

I am experiencing an issue where I can run a flask app in pycharm

#

but it doesn't work from the command line

#

I think because pycharm adds the project source to PYTHONPATH

#

has anyone experienced this issue?

calm plume
#

From my understanding, that's a browser security feature that's stops you from using paths that resolve to your local computer rather than a specific url

supple bramble
#

Is it really worth it to integrate ReactJS with Django (not DRF)? Why do people even want to do that? Are there any benefits or something?

#

Imo templates are really good and easier to work with and get everything done, and afaik there isn't really any good reason to use React with Django, but I might be wrong so can someone maybe clear this out?

inland oak
supple bramble
#

define complex logic here?

#

I mean yes that's true but with django?

inland oak
#

They complement each other

#

Django does what react cant

supple bramble
#

We can't create single page apps when using django and react right

inland oak
#

React can what dj cant

supple bramble
#

that's what i am asking, when using react with django, what benefits does it give over django templates?

inland oak
#

We can create single page app with dj and react

supple bramble
inland oak
#

Or each dj app could spawn micro react app

supple bramble
#

That sounds very ineffectient tbh

inland oak
#

It depends on logic site u need

slender timber
#

how to code py in pc?

#

can anyone help me make like discord

supple bramble
slender timber
#

we will 50/50 earnings

inland oak
slender timber
#

lz

#

lz

#

plz

inland oak
#

React alliws writing front with multiple states

#

For one page

supple bramble
#

austt this isn't a web dev related question tho

slender timber
#

i want to make a minecraft

supple bramble
slender timber
supple bramble
#

sorry I can't

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @slender timber until <t:1627201327:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

jagged lark
#

!warn 831868294779633674 Please don't spam ping people when requesting for help, and re-read our #code-of-conduct. Consider this mute to be 3h long.

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied warning to @slender timber.

inland oak
supple bramble
#

speed is the only thing then right?

inland oak
#

Speed... And what is available in terms of js animations

supple bramble
#

you can use js in templates too tho

inland oak
#

You can have literally a game paying in js for client

supple bramble
#

No one is stopping you from using js in html templates right

inland oak
#

But with react... You just use arrays of js libraries. More set of ready to use front tools

supple bramble
#

What kind of libraries would you need to use? Most of the time they are related to auth and routing which you don't need to care about in django, yes maybe lottie files for animations but quite sure you can do something like that with pure js too

inland oak
#

Not sure. I saw react only from afar. I can say that they have that Redux library, that allows them to control state of multiple things going in front more easily

#

It makes them use Design Pattern State at library level I think

inland oak
#

this thing mentions front tools for frontenders

zealous moth
#

Hey guys I need help is setting environmental variables in django.

native tide
#

trying to pass in the relative path gave an 404

#

same as anything else

native tide
rare wasp
#

Anyone knows how can I open a url which return xml response and parse it in django

long jackal
#

Why is my background not filling the whole screen? There is a bit of white space at the bottom, as seen in the image below and you can also scroll up and down and even right and left. In this website www.calcbot.ml the background is filled exactly according to the screen size

This is the page's code file

{% extends "layout.html" %}
{% block content %}
    <h1 class="abspos" style="text-align:center;margin-top: 20px;color: white">SoLigh</h1>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/trianglify/1.1.0/trianglify.min.js"></script>
    <script>
        var colors = ['#17b023', '#c9bb49', '#17b023', '#adc947']
        var pattern = Trianglify({
            width: window.innerWidth,
            height: window.innerHeight,
            cell_size: 75,
            x_colors: colors,
            y_colors: colors,
            stroke_width: 1.51
        });
        document.body.appendChild(pattern.canvas())

    </script>
{% endblock content %}
raw compass
fading gazelle
#

Hey!!

fading gazelle
#

Hey!!! I want this check box outside the box but these 2 elements(The list and the checkbox) should be connected(because I should be able to make the opacity low when clicked the check box).I tried with position absolute and stuff like that but I couldn't make it
html

<html lang="en">
  <head>
    <link rel="stylesheet" href="styling.css" />
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>To Do List</title>
  </head>
  <body>
    <div id="main-box">
      <h1 id="heading">To Do List</h1>
      <p id="date">18-07-2021</p>
        </div>
    <form id="input">
    <div>
        <input type="text" placeholder="Add a task......" id="add_task">
        <button type="button" id="add" href="#">+</button>
    </div>
    </form>
      <div id="tasks">
        <ol>Have To write Notes
        <input type="checkbox" id="scales" name="scales"
        checked>
      </ol>
      </div>
    </div>
  </body>
</html>```
CSS
```#add {
  line-height: 0.1;
  letter-spacing: 0em;
  font-weight: 500;
  font-style: normal;
  font-size: 66px;
}
div ol {
  position: relative;
  background-color: rgb(0, 0, 0);
  margin: auto;
  width: 50%;
  border: 1px solid rgb(255, 255, 255);
  padding: 14px;
  text-align: center;
  margin-top: 80px;
  color: azure;
  font-size: 25px;
}

.scales{
  position: absolute;
  margin-top: 0px;
}```
mystic wyvern
#

Hello there , somthing I would know
is why we use post method when we delete token instead of use delete method

long jackal
mystic wyvern
mystic wyvern
vestal hound
mystic wyvern
#

Not this what I mean, I mean I learnt to do that

rare wasp
rare wasp
brisk wadi
#

Hello, so I have a python script that has a while loop, prints like 4 outputs per sec,
now I need these 4 outputs to keep updating the html without the need to reload, so like the html keeps updating nearly in real time with the new outputs, any help?

#

I really can't figure it out

vestal hound
#

but it is a bit odd

#

you will see APIs that use POST for more or less everything

#

there are restrictions on non-POST requests

#

that don't apply to POST requests

brisk wadi
#
from flask import Flask
from threading import Thread
import string
import random

app = Flask('')

def sentence():
    while True:
        return random.choice(string.ascii_letters)

@app.route('/')
def main():
    return sentence()

def run():
    app.run(host="0.0.0.0", port=8080)

run()

I tried this which outputs a letter in a while loop, but the letter won't update unless I reload, also, it removes the previous letter...

loud matrix
#

How do you make mp3 file play in the background as soon as you land on a page?

calm plume
vestal hound
#

in 2021

loud matrix
#

oh okay

#

Thanks for telling me ^^

calm plume
#

You'll want to move your file out of the templates directory and into a directory called static

#

And then the template language you're using should have a tag for static urls (but if that's just regular html, you'll want to use a relative path rather than one that compares to the root of your computer)

rose plover
#

Can anyone help me with html, I don't know how to put an image on the website, that's on my computer. So I have the file saved in my computer but I tried anything and nothing works, it just shows this little image not found thing on the website.

#

this is how it looks like, I tried putting it in a folder in visual studio and stuff but nothing works

eternal blade
#

Try passing in the absolute path

rose plover
#

this is the error in visual studio

next comet
rose plover
#

@next comet thank you so much, it works

next comet
native tide
calm plume
#

Django? Flask? FastAPI?

jovial cloud
brisk wadi
mint folio
brisk wadi
#

that's it

#

I am using flask for the deployment

mint folio
#

Well you will need some js for that as the other user said if you want to update content without page reload. You can also have auto reload with meta refresh but that might not be what you want.

jovial cloud
brisk wadi
brisk wadi
mint folio
#

Ok let me see if I have something

jovial cloud
brisk wadi
#

Aight ty

real remnant
#

I'm trying to make a video calling website and i have never used python to make a website

glossy scroll
#

heyall

#

anyone here experienced in django admin?

#
class Order(models.Model):
    class Meta:
        ordering = ('-date_created',)

    class Status(models.IntegerChoices):
        PEN = 0, "PENDING"
        PAI = 1, "WAITING VERIFICATION"
        ECD = 5, "BAD ESEWA CODE"
        OOS = 4, "OUT OF STOCK"
        DEL = 2, "DELIVER"
        COM = 3, "COMPLETE"
    profile = models.ForeignKey(Profile,on_delete=models.CASCADE,related_name='order',null=True)
    status = models.PositiveSmallIntegerField(choices=Status.choices,default=Status.PEN)
    date_created = models.DateField(default=datetime.date.today)
    ship_to = models.ForeignKey(Address,on_delete=models.CASCADE)
    email = models.EmailField(null=False)
    phone = models.CharField(max_length=15,blank=False)
    transaction_code = models.CharField(max_length=12,unique=True,blank=True,null=True)

class Address(models.Model):
    country = models.CharField(max_length=64)
    district = models.CharField(max_length=64)
    municipality = models.CharField(max_length=64)
    ward_no = models.PositiveSmallIntegerField()
    street = models.CharField(max_length=256)
    
#

i have this two models and i want to unpack the 'ship_to' field in the admin page

#

i tried using inline admin but django throws an error saying it needs a foreign key in the address model

#

currently im limited to

glossy scroll
#

well i managed to do it using readonly fields and calling individual functions

#
class OrderAdmin(admin.ModelAdmin):
    model = Order
    inlines = [OrderItemsInline,]
    list_display = ['get_email','id','email','phone',
                    'transaction_code','status']
    list_filter = ['status']
    search_fields = ['profile__user__email','id','email','phone']
    readonly_fields  = ('profile','ship_to','get_country','get_district','get_municipality','get_ward_no','get_street')
    fieldsets = [
        ('General',{'fields':('profile','status','date_created')}),
        ('Details',{'fields':('email','phone','transaction_code',)}),
        ('Delivery Address',{'fields':('get_country','get_district','get_municipality','get_ward_no','get_street','ship_to')}),
        ]

    def get_email(self, obj):
        return obj.profile.user.email
    get_email.admin_order_field  = 'user'
    get_email.short_description = 'Profile email'

    def get_country(self,obj):
        return obj.ship_to.country
    def get_district(self,obj):
        return obj.ship_to.district
    def get_municipality(self,obj):
        return obj.ship_to.municipality
    def get_ward_no(self,obj):
        return obj.ship_to.ward_no
    def get_street(self,obj):
        return obj.ship_to.street
    
    get_country.short_description = 'country'
    get_district.short_description = 'district'
    get_municipality.short_description = 'municipality'
    get_ward_no.short_description = 'ward_no'
    get_street.short_description = 'street'
#

like so , how bad is it?

native tide
#

Hi, how can I block access to a specific page (exmpl.com/profile) to those who have not yet logged in (python and Django)

glossy scroll
#

If you're using Class based views you can use LoginRequiredMixin

#

its this import from django.contrib.auth.mixins import LoginRequiredMixin

#

you use it like so:

#

@native tide

native tide
calm plume
native tide
#

okay

glossy scroll
#

and if you're using function based views you can >

#
def index(request,*args,**kwargs):
  if request.user.is_authenticated():
    messages.error(request,'You need to login')
    return redirect('app:login') # Redirect to login page
  else:
    return render() # Your page here
native tide
#

i find a decorator to use in this case

#
@login_required(login_url='/login/')
def Profile_user(request):
    return render(request, "profile_user.html")
#

imports

from django.contrib.auth.decorators import login_required

stark tartan
#

  class Post(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    caption =models.CharField( max_length=100,blank=True)
    history = HistoricalRecords()
    video = models.FileField(upload_to='videos/',blank=True)
    tagged_people=models.ManyToManyField(User,related_name='tagged_people',blank=True)
    like_people=models.ManyToManyField(User,related_name='like_people',blank=True)
    posted=models.BooleanField(default=False)
    created =models.DateTimeField(auto_now_add=True)
    updated=models.DateTimeField(auto_now=True)


class ReportPost(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    description =models.CharField( max_length=100,blank=True)
    created =models.DateTimeField(auto_now_add=True)
    post=models.ForeignKey(Post,on_delete=models.CASCADE)
    def __str__(self):
        return self.post.user.username +'::' +str(self.description)

I want to get the Posts which are not in ReportPost model pls tell me queryset for this

winter pine
#

why is it formatted so disgustingly?

opaque rivet
# stark tartan ```python class Post(models.Model): user = models.ForeignKey(User,on_dele...

Instead, I would give Post and ReportPost a one-to-one relationship (as one reported post corresponds to one post). Then, I would add a BooleanField called reported to the Post model. I would override the .save() method of the Post model, or add a post_save signal to ReportPost, which will check if there are any objects on the other side of the one-to-one relationship, if so, reported=True.

Then you can just filter all objects by the reported field...

opaque rivet
#

it returns a boolean, which isn't callable

keen berry
#

finally made my first flask app after a month! pls check it out lmfao
address: localhost:8000 or 127.0.0.1:8000

vestal hound
terse vapor
#

on insta, the message is in a <span> tag while inspecting, however, I am able to use selenium xpath to find the message but not the latest one, is there a way that i can use time to filter out the message to find the latest one?

#

is it possible for me to store all the message into a list than use list[:-1] to find it?

mint siren
edgy anvil
#

i am working on a flask web app with my firends and we needed a way to update graphs on our dashboard page so they made a dashboard.py file. Is there any way to implement this file into my flask webapp. Specifically i want to go to this dashboard page once the user has logged in. But i have no idea on how to do this can someone help? thanks!

stark tartan
stark tartan
edgy anvil
stark tartan
#

And did.you are using html css javascript in frontend

edgy anvil
edgy anvil
edgy anvil
stark tartan
#

Or maybe a button to update graphs

edgy anvil
#

i c

#

we aren't updating them particularly just trying to make the grpahs more interactive

edgy anvil
#

@stark tartan can i do the same thing with plotly graphs

lime mist
#
from defaults import server_url
import asyncio
import socketio
import json

sio_client = socketio.AsyncClient()


# Main Connection
async def main():
    await sio_client.connect(server_url)
    await sio_client.wait()


def run_sio_client():
    asyncio.run(main())


# Default Events
@sio_client.event
async def connect():
    print(f"Connected!")


@sio_client.event
async def disconnect():
    print("Disconnected!")


@sio_client.event
async def sid(sid):
    print(f"MY_SID: {sid}")
``` ```python
from src.helpers.sio_client import run_sio_client, sio_client
import threading
import time


async def test_ping():
    await sio_client.emit("test_ping")

t1 = threading.Thread(target=run_sio_client)
t1.start()

while not sio_client.connected:
    print("NOT CONNECTED, Trying again...")
    time.sleep(1)

test_ping()
print("REACHED HERE!")```how do run `test_ping()` ?
I want to connect to socket.io server and use `sio_clien`t to emit events on some logic
#

OUTPUT

#
NOT CONNECTED, Trying again...
NOT CONNECTED, Trying again...
NOT CONNECTED, Trying again...
MY_SID: nNuJg3vJzdkADd71AAAN
Connected!
D:\Coding Stuff\UpWorkStuff\LinkedInDelivery\li_worker\run.py:16: RuntimeWarning: coroutine 'test_ping' was never awaited
  test_ping()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
REACHED HERE!```
#

script just hangs after this

edgy anvil
#

O ok

keen berry
#

im joking

night radish
#

I haven't learned flask yet but I have a question, if I upload an image in my flask instance and post that link on discord , can discord render that image?

stark tartan
night radish
#

Ah yes ofc

stark tartan
night radish
#

'of course'

stark tartan
night radish
#

Oh no it's fine .. we've all been there 🤗

long jackal
#

how do I make this symmetrical?

its the text length that does this, if they are all the same length in characters they will be equal
but they aren't so how else would I fix this?

swift dune
#

heyho my friends i have a problem with my flask app
it won't run because of an error that i can't find
my server says the error is in line 44 but there is no obviews error with the code

the app runs fine in pycharm

lavish prismBOT
swift dune
#

in my ide

#

please tag me

jovial cloud
swift dune
#

in the html file ?

native tide
#

i downloaded a free template from internet, i want to change the theme color how can i do it

native tide
#

it was working, after the migrations it wont work anymore

eternal blade
#

Looks like there is a problem in serving static files

native tide
#

literally the dashboard is working, only the homepage get this errors

#

ok i fixed

#

im dumb i didnt see that the folder with css and js was outside home folder

next comet
#

anyone can tell me how can i debug django tests in vscode, i tried to search in the net but nothing seems helpful and explanatory

craggy laurel
#

I get this.

#
@app.route("/")
def home():
    return render_template("index.html")



if __name__ == "__main__":
    app.run(debug=True)
``` That's the code about the website
#

in my bot file

next schooner
#

and why do we even bother marking it with is_safe? Just so that Django doesn't have to do unnecessary work and escape output if we know it will be safe?

opaque rivet
#

@stark tartan a One tovOne relarionship between Post and ReportedPosts

native tide
#

why when I modify the site's css file, nothing changes?

#

i have to reload somethin? (i tried to rerun the server but nothing)

#

ok i fixed

#

by opening it on incognito

#

(the changes didnt appear for the cache of the site maybe )

#

Hey everybody, i am trying to setup Nginx for my server. Is UWSGI necessary?

patent cobalt
#

You don't have to use uWSGI if you want to go the WSGI-route (which is the most common route). Gunicorn is also a popular option.

native tide
#

What is the difference between them?I don't know much

#

I am a beginner in server deployments, i don't know anything related to WSGI and Gunicorn

#

Only thing i know is NGINX helps to modify some protocols for server requests

patent cobalt
#

NGINX does not "know" how to talk to a Python-application. Django supports WSGI, which is a standardized way to talk to Python web applications. uWSGI and Gunicorn do that "translation step", so you get something like client <---> Nginx <---> uWSGI <---> Python app

native tide
#

Sebastiaan can u help me?

patent cobalt
#

@native tide Your question does not seem to relate to this channel. I think it's best to open a help channel (see #❓|how-to-get-help) or to find a topical channel that does firt your question.

native tide
#

What Frontend i use with Flask?

native tide
#

My bad am sorry

patent cobalt
#

So, it's not something NGINX knows how to talk to on its own

patent cobalt
native tide
#

I am asking because i face with this problem whenever i need to configure something with UWSGI

sudo service uwsgi start
Job for uwsgi.service failed because the control process exited with error code.
See "systemctl status uwsgi.service" and "journalctl -xe" for details.

I think i will try gunicorn. Thanks for the help

native tide
patent cobalt
#

There's no single thing that works best, although flask would probably play a slightly different role if you use a full-fledged front-end app like react/angular