#web-development

2 messages · Page 231 of 1

novel stream
#

not only that but let's say yes

hollow dragon
#

I think it will work bcus my whole config and app was built for heroku, so PostgreSQL will have the "exact" DATABASE_URI

novel stream
#

yep, I'm also thinking in this way

agile bison
#

Hello guys,
I have a problem with updating json fields in flask sqlalchemy. Does anyone have any idea how to solve it. Thanks!

novel stream
agile bison
#

@novel stream ```def campaign_detail(campaign_id, campaign_service=Provide[Container.services.campaign_service]): # campaign_service=Provide[Container.services.campaign_service]
try:
selected_campaigns = campaign_service.search_by_campaign_id(campaign_id)
except Exception as i:
print(i)
raise

if request.method == 'POST':
    active_from = request.form.get('active_from')
    active_to = request.form.get('active_to')
    new_values = {}
    results = request.form
    for key, value in results.items():
        new_values[key] = value
        print(value)
    try:
        campaign_value = CampaignService.updated_values(selected_campaigns["campaign_value"], new_values)
        selected_campaigns["campaign_value"] = campaign_value
        selected_campaigns["active_from"] = active_from
        selected_campaigns["active_to"] = active_to
        print('passed')
        return redirect(request.url)
    except Exception as i:
        print(i)
        print('i1')
        return ''
elif request.method == 'GET':
    try:
        campaign_value = CampaignService.extract_values(selected_campaigns["campaign_value"])
        return render_template("list.html", title = campaign_id, campaign=selected_campaigns, campaign_value=campaign_value)
    except Exception as i:
        print(i)
        print('i2')
        raise```
novel stream
agile bison
#

@novel stream @staticmethod def updated_values(campaign_value_old, updated_values): if isinstance(campaign_value_old, str): print('str') data = json.loads(campaign_value_old) if isinstance(campaign_value_old, dict): print('dict') data = campaign_value_old #print(type(campaign_value_old)) else: RuntimeError() try: print('+') for key, d in data['value'].items(): if type(d) == dict: var = d['variable'] if var[0] in updated_values: data['value'][key]['value'] = [updated_values[var[0]]] #print(type(data)) return data except Exception as i: print(i) return ''

novel stream
agile bison
novel stream
#

So the problem is that json field is not updating?

agile bison
#

In the terminal I have an output of new (updated) values ​​but they are not displayed in "list.html" when redirecting or not updated in the database.

novel stream
#

and it is in this updated_values that this should happen?

agile bison
#

Yes. the problem is with json-sqlalchemy relation and I saw on the sqlalchemy documentation that I need to use nested MutableDict but still there is no progress.

novel stream
agile bison
#

@novel stream no problem mate 🙂
I am still learning also, thanks anyway.

native tide
#

Does anyone know how to change permissions on django? Can I do it from /admin or do I need to use code?
I cant figure it out

novel stream
native tide
novel stream
native tide
#

Unless the orange selection is supposed to be how I pick permissions? If so thats very unintuitive

novel stream
native tide
hidden gulch
#

hello, i've been trying to use sqlalchemy's regex pattern match to find all occurences of a certain word in the rows of a table in my DB.

Im doing something like select(myTable).filter(myTable.c.some_column.op('~')(r"\b{}\b".format("word")))

This however doesnt seem to work, is there something Im missing? Im using python3.10 btw

hollow dragon
vivid whale
#

Not so sure how to use this, is this incorporated with my IDE (pycharm) or is it an app to install?

golden bone
vivid whale
golden bone
#

The changes in your local repo will be pushed to the repo on GitHub.

vivid whale
#

So itll create a copy of the repo at first then any additons or subtractions will replace that code

#

I see

golden bone
vivid whale
#

thanks

hollow dragon
#

Can anyone help me with flask, docker?

frank shoal
#

ask your question.

hollow dragon
#

Everything works fine, image is created but when I run the container it immediately stops

frank shoal
#

Can you post your Dockerfile? Maybe a log?

#

And the command you use to run it

hollow dragon
#

Should I call you or its fine here?

frank shoal
#

here is fine.

hollow dragon
#

its from a tutorial

#
FROM python:3.8-alpine

# copy the requirements file into the image
COPY ./requirements.txt /microblog/requirements.txt

# switch working directory
WORKDIR /app

# install the dependencies and packages in the requirements file
RUN pip install -r requirements.txt

# copy every content from the local file to the image
COPY . /app

# configure the container to run in an executed manner
ENTRYPOINT ["./boot.sh"]

CMD ["app.py" ] ```
#
source venv/bin/activate
flask db upgrade
exec gunicorn -b :5000 --access-logfile - --error-logfile - microblog:app```
#

but I've tried without boot.sh and it still doesn't work

#

maybe because I use WSL? but it doesn't work with Docker Desktop either

golden bone
hollow dragon
#

Hopefully it will be still fine. My web app runs but docker somehow fuckd up. Im gonna have an internship interview tomorrow.

novel stream
hollow dragon
novel stream
#

yes

hollow dragon
#

i think im just gonna give up, because deploying to heroku with docker a venv/flask/postgresql web app is quite pain in the a$$

#

i've learned enough docker imo for this internship lmao...hope i don't need this much complexity

#

as a "junior"

ionic raft
#

Does anyone have any experience with implementing Premium TinyMCE features in Django?

native tide
#

is there a way to hook up a domain with flask directly?

elder walrus
#

Hey guys, Is there a way to get the name of the uploaded file in django?

crisp dragon
#

hey i need some help in my django project

dusk sonnet
#

hey, iv been tryna figure out how to get connected users in Django Channels but havent made any progress. if anyone can help id really appreciate it, thanks!

wind dove
mystic wyvern
#

The file name is stored in name attribute

novel stream
mystic wyvern
lapis spear
#

if i delete this file on my django project will i reset my database from scratch?

#

im learning django by creating the backend of a website and the further i advance i realize that the structure of my models are kinda off so i want to start from scratch of my database

#

if i delete that file and just edit my models.py and run makemigration and migrate will it be all ok?

mystic wyvern
novel stream
lapis spear
high scarab
#

what is the purpose of a nested Meta class in a django form class?

#

it seems to specify the model corresponding to the form and the field names, but for what purpose?

lapis spear
#

@mystic wyvern@novel streamalright thank you sirs

novel stream
weak blaze
#

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *

class MainWindow(QMainWindow):
def init(self):
super(MainWindow, self).init()
self.browser = QWebEngineView()
self.browser.setUrl(QUrl('http://google.com'))
self.setCentralWidget(self.browser)
self.showMaximized()

    # navbar
    navbar = QToolBar()
    self.addToolBar(navbar)

    back_btn = QAction('Back', self)
    back_btn.triggered.connect(self.browser.back)
    navbar.addAction(back_btn)

    forward_btn = QAction('Forward', self)
    forward_btn.triggered.connect(self.browser.forward)
    navbar.addAction(forward_btn)

    reload_btn = QAction('Reload', self)
    reload_btn.triggered.connect(self.browser.reload)
    navbar.addAction(reload_btn)

    home_btn = QAction('Home', self)
    home_btn.triggered.connect(self.navigate_home)
    navbar.addAction(home_btn)

    self.url_bar = QLineEdit()
    self.url_bar.returnPressed.connect(self.navigate_to_url)
    navbar.addWidget(self.url_bar)

    self.browser.urlChanged.connect(self.update_url)

def navigate_home(self):
    self.browser.setUrl(QUrl('http://programming-hero.com'))

def navigate_to_url(self):
    url = self.url_bar.text()
    self.browser.setUrl(QUrl(url))

def update_url(self, q):
    self.url_bar.setText(q.toString())

app = QApplication(sys.argv)
QApplication.setApplicationName('My Cool Browser')
window = MainWindow()
app.exec_()

#

error:

#

:\Users\Laptop\Downloads\my_cool_browser-main\my_cool_browser-main\main.py", line 4, in <module>
from PyQt5.QtWebEngineWidgets import *
ModuleNotFoundError: No module named 'PyQt5.QtWebEngineWidgets'

#

csn someone help

urban dirge
#

you need to install the module

weak blaze
#

how

#

@urban dirge

urban dirge
#

try to find it in pip

weak blaze
#

the code

#

pls

#

for the pip

#

install

#

webengie

#

engine

urban dirge
#

look up the module name in pip

weak blaze
#

oj

urban dirge
#

or look up the error in google

weak blaze
wide canyon
#

Hello. I'd like to share a Django package I created. Is that allowed ?

dusk sonnet
#

cant find anything online on it as well

wide canyon
noble spoke
#

what does tornado offer that would make anyone pick it over flask or fastapi for small APIs

native tide
#

Is Wordpress worth learning

native tide
#

Best web dev road map for noobie?

mystic wyvern
mystic wyvern
gleaming frigate
#

How do I do an inner join in django?

mystic wyvern
dusk portal
#

oh

golden bone
#

Uh, by pressing enter? Or am I not understanding the question?

sudden sierra
#

I'm not sure

golden bone
#

oh @native tide If you mean you want to automatically wrap after = instead of after ,, try #editors-ides (and tell them whether that's VS Code or what)

ionic raft
#

Does anyone have experience with setting up JWT Authentication in Django? I'm trying to connect with an external API that needs JWT Auth.

uneven basin
#

in flask is it possible to define routes in a module and import them into the main module?

mystic wyvern
ionic raft
#

I'm at the point where I am trying to connect with Dropbox instead. Tutorials on jwt focus on user Auth. I don't need that. I need to Auth with the Tiny Drive API

mystic wyvern
#

You want to authenticate yourself to that drive and then return an jwt that can be authorize you to access data from this tiny drive?

ionic raft
ionic raft
proper hinge
#

Seems like you could do the same thing in Django using DRF to create the endpoint and pyjwt to encode the token with the private key

#

Disclaimer though, I've not attempted that.

terse sorrel
#

hey guys is there anyway i can build an admin interface ( with pretty much the same functionality as the one provided with django) using a frontend framework

fair lichen
#

Hi all,
Super noob level question here. I'm a working data scientist, and I'm happy working in python, and with coding in general. I've never built a website, and I'd really like to dip my toes. But I've got absolutely no idea where to start, and there seem to be so many options.
Netlify? Django? Flask? React?
I'd really appreciate any pointers on where's good to start. Thanks!

ionic raft
proper hinge
#

I don't think it's a matter of whether Django is supported because they just define an interface which they expect the endpoint to have.

#

Any framework that can create a POST endpoint should work.

#

But it's their product and they know best presumably, so let's see what they have to say.

proper hinge
proper hinge
native tide
# fair lichen Hi all, Super noob level question here. I'm a working data scientist, and I'm ha...

If you're looking for pedagogy Flask is better.
If you're looking for something that looks good with good performances, without much initial effort go for Django.

Flask: you build everything from scratch or you download Flask components.
Django already comes with a bunch of features such as authentication, templating, orm. Makes your life easier.

I would suggest you start with flask, build everything you need by yourself, then when you get most topics/components, you go for django

fair lichen
#

OK that sounds great

#

And to deploy it, do I need to buy a domain name?

#

Or is there a netlify equivalent which will do it for free?

proper hinge
fair lichen
#

Ah great, thatnks!

rich dove
#

Hey guys, I've posted this on stack overflow so I won't repeat the question, but if anyone knows the answer help would be greatly appreciated! https://stackoverflow.com/questions/72555877/fetch-path-from-url-and-use-it-within-python-script

native tide
#

register and login /logout is not work

#

User has no customer.

dusk sonnet
# mystic wyvern Can you tell more details what you want to do

so iv created a chat app and i want to display how many users (if any) are currently connected (online) to the chat. Now i understand that it must be done via the connect and disconnect functions because thats what detects when a user has connected to the websocket but im not sure how to store that. Iv tried using a manytomany field in my model to store the users who connect but i couldnt get it working

#
async def connect(self):
        self.room_group_name = 'chat_%s' % ''
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )
        await self.accept()
    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )
mystic wyvern
# dusk sonnet so iv created a chat app and i want to display how many users (if any) are curre...

You can set a status filed in your model like this

ONLINE = 'online'
   
   STATUS = (
       (ONLINE, 'online'),
       (OFFLINE, 'Offline '),
   ) 
status = models.CharField(
       max_lenght=10, choices=STATUS,
       default=ONLINE
   )```
and set true when the websocket is connect and false when it is not, or  make an online counter in your model and increase it by 1 when a websocket connect and decreaset by 1, if the counter equal to zero, then the user is offline
mystic wyvern
dusk sonnet
stiff ferry
#

is there a way to verify the django superuser email when created?

dusk portal
stiff ferry
gleaming frigate
mystic wyvern
main jasper
#

Flask - User file upload. Application factory setup; Windows.
config has:

UPLOAD_FOLDER = 'static/uploads'

Trying to save a file to path:
os.path.join(current_app.config['UPLOAD_FOLDER'], filename)

save throws an error on path:
FileNotFoundError: [Errno 2] No such file or directory: 'static/uploads\my_workbook.xlsx'

but works with:
os.path.join(current_app.root_path, current_app.config['UPLOAD_FOLDER'], filename)

What's wrong with my setup? Most tutorials dont use root app path to build path.

novel stream
native tide
#

If I know the basics of html and css can I move on to js

eternal blade
#

Is there something like request.build_absolute_uri but for WebSockerConsumer's

native tide
#

What should someone do if they aren’t a problem solver

novel stream
#

Take a look at these playlists, you might find something useful https://www.youtube.com/c/veryacademy/playlists

spare lodge
#

hlo

cobalt creek
#

Hi I need some help with WordPress
I displayed all the events and now I just wanted a search bar to search those events any body have any how to do so ?

native tide
#

In flask, can you only get the name and value of <input> elements using request.form?

#

If so, is there a way of getting the innerHTML value of a <button> in flask, using something like request.form?

frank shoal
#

If you use form.submit(), yes

frank shoal
#

Instead of using <button> try using <input type="button">

#

you can have multiple buttons with the same name and different values

native tide
#

I was creating new button elements for each new keyword entered, the buttons are just for design they aren't actually submitting anything. I'm just working around it by adding the innerHTML of each button to a js array, which i put into an invisible text input field that is then recieved by flask using the name. @wooden ruin

wooden ruin
#

why not use hidden input types?

native tide
daring isle
#

In react , how are you guys handling api calls after log in for a user ?
I’m trying to decode JWT and use the user id to query related tables .

It’s working but I’ve had to useEffect catch it and refresh the page manually after log in - as the first runs are empty and the page doesn’t re-render

#

I’ve been stuck for like 3 days . I can’t find a solution online

pulsar tendon
#

i need help

#

im trying to do the unorderd list in html but when i try it it didnt work

#

this is the code
<html>
<body>
<img src = "pancake.jpg" title = "pancake" height = "350" width = "550">
<h2> Pancake Recipe</h2>
<h1>Ingredients</h1>
<ul>
<il>2 eggs, Large</il>
<il>1 small can, Alaska evaporada</il>
<il>1 1/4 cup, all purpose flour</il>
<il>2 tsps, baking powder</il>
<il>3 sticks, butter</il>
<il>1 cup, water</il>
</ul>
<p> Instructions</p>
<ol>

</ol>

daring isle
#

You need closing tags on html and body </body> </html>

timber swan
pulsar tendon
lone jackal
daring isle
# daring isle I’ve been stuck for like 3 days . I can’t find a solution online
///for the JWT decode
  const [decoded, setDecoded] = useState('')

///for the user info i was trying to retrieve
  const [userinfo, setUserInfo] = useState([])

  
  useEffect(() => {    

    console.log("Trying decode")
    var token = jwt_decode(localStorage.getItem('refresh_token'))
    console.log(token.user_id)
    setDecoded(token.user_id);
    console.log(localStorage.getItem('refresh_token'))

  },[localStorage])


  useEffect(() => {

    async function fetchData() {      
      const request = await axios.get(`users/id/${decoded}`);
      console.log(request.data);
      setUserInfo(request.data)
      return request;
      
    }
    fetchData();
  }, [decoded]);

This works for my problem of auto refreshing

ionic raft
#

ah yes...just spent 2 days solving a problem to discover two more 🤪 The joys of development.
On the plus side, with experience I'll discover at least twice as many problems as I intend to solve. #WillAlwaysHaveSomethingToDo

quiet cipher
#

hi guys

#

is django for beginners by william s.vincent a good book?

#

does this work for you guys?

#

command to create a directory

#

for me it says

the system cannot find the specific path
#

when i input cd~/Desktop

ionic raft
# quiet cipher command to create a directory

I've not read that book. However, it looks like you're being walked through step by step to create a project. Whenever I get stuck on syntax problems it can be good to search Stack Overflow.

ionic raft
#

I am a fan of including video tutorials in my learning experience. Here's a fav of mine:
https://www.youtube.com/watch?v=UmljXZIypDc&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p

In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic application running in our browser. Let's get started...

The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Django_Blog

Flask Tutorials to cr...

▶ Play video
quiet cipher
#

how did u learn django

#

did u use any books?

ionic raft
#

I started with that video...and then built projects. Started april 15, 2021. My profile has sharable projects I've deployed

quiet cipher
ionic raft
quiet cipher
#

thats true

#

alr ill go through the vids thx

ionic raft
#

Some software engineering concepts can be brutal to rely just on reading for. Seeing it done (how it should look), replaying...let's me dig in until i get it. Then books flesh out the theory 😉

#

Corey is solid. Laid a foundation for me that has influenced every Django project I've built or deployed

quiet cipher
#

after the video series where did u continue learning django

ionic raft
#

But two scoops is definitely a read after you've been using Django for a while. Unless you're super-nerd-genius-savant of course.

quiet cipher
#

ah alr

ionic raft
#

I actually started with a Python bootcamp. Laid the foundations down, went to Flask, then to Django.

#

Never looked back. Been coding Django for most of a year solid now. Sometimes 12-14 hours a day...love it

#

The good news is when it comes to Python to get a lot from Django you don't need to be super-savant-genius coding Machine Learning systems and Neural Networks. The Django Framework is wizard tho.

#

if you're new to web development frameworks and web servers, then Flask is a good step towards Django as well.

#

Flask will get you thinking about Python in a particular way, leverage a lot of very clever work already done on a focused niche (web server/development).

#

Then if you're goal is complex web applications then Django will blow your mind, bruh 😉

quiet cipher
#

i see

ionic raft
#

You have much experience with python?

quiet cipher
#

uh not much tbh

ionic raft
#

Or with software engineering generally?

quiet cipher
#

prolly like 3 months

#

basics

#

like im not even good with oop

ionic raft
#

3 months is enough. So long as you've got core concepts down: Lists; dictionaries; logic; debugging; etc...

ionic raft
#

You don't need OOP really. Sure, classes are used for data modelling for example, but Django development is user-request driven. You'll expand your Python chops gradually, as you build web applications.

#

Cool. The great thing about Django is that you will continue to expand your knowledge of Python, but in a very focused way. Plus, there's a significant community, and many libraries getting stuff done.

quiet cipher
#

yep

ionic raft
#

Now. OOP is baked into Django. The point is, some clever peeps have done a lot of heavy lifting for you.

#

So custom building your own OOP isn't a gateway unless you find a solid use case for it to be.

quiet cipher
#

yeah along with django/flask ill be learning oop

ionic raft
#

Getting the concept of OOP will help you when read about the underlying framework and theory.

quiet cipher
#

like on weekends

ionic raft
#

Have lots o fun. It's a great community here. Take in Corey's tutorial and get some basics down. What he does with Class Based Views and some specific approaches continues to be relevant for me over a year later.

#

Oh. And don't worry about the profile pic part. You don't really want to be storing media files (files you upload) on your server.

#

The fist big project I did I literally had to decouple the profile pic part. Quite amusing when I look back on it. It's not that what he does is wrong. Rather, using your Django web server to store media files isn't optimal, mainly for security reasons. However, so long as you don't code that particular piece of knowledge into production it's good to see a particular use case covered

quiet cipher
#

uhh
so i created a django project using

python -m django --version startproject
#

since django-admin doesnt work for me

#

so i successfully created the project

#

but i cant find the folder

#

any way to find the path?

#

ohhhh i got it yay

#

thxx

#

hm il just move it to desktop

#

man why do i get so many problems

#

now when i input

cd django_project/
#

it says

The system cannot find the path specified.
quiet cipher
#

finally i launched my web server yay

daring isle
thorny urchin
#

Hello Guys. Anyone here?

quiet cipher
#

hi

thorny urchin
#

Hi. Well, I need help with respect to my project.

#

So, the thing is:

#

I have an assignment.

#

A group assignment.

#

Where in I am supposed to make a website, by using only the front end, that is HTML and CSS.

#

I am completely a noob to it, so I need help with the same.

#

Is anyone willing to help me?

native tide
#

hello im creating a personal website with flask and bootstrap , i learnt html 2 yrs ago so im kinda rusty, and for some reason the video which i add into this personal website isnt working

#
        <video src ="G:\Python\website\keyboard.mp4" width = '600' height="600" controls>
    </div>```
#

would someone help me

#

the indentation is fine discord is wack

tiny snow
#

Try using a relative path. Maybe the video file is not served, you can check the Sources in the dev tools

hardy apex
#

Hi everyone, new to using Flask and I want to send variable information to another script and then access it in the other, how would I go about doing this? Here is a picture of my routes.py that I am using

#

On line 20 is where I am trying to send variables 'name,email,message' to mailing.py but I am not sure how

#

if you have any idea please @ me

ionic raft
ionic raft
quiet cipher
#

btw i checked your website
great job dude it looks lit

ionic raft
quiet cipher
#

lanesflow

ionic raft
# quiet cipher lanesflow

Cool. Yes, that's a business consultant app. Got some real world clients using that as a part of training I deliver. However, it's missing a key piece that I will get back to (and requires me learning React)

quiet cipher
#

its an inspiration for me (im still not able to create a homepage app 😅 😭 )

ionic raft
lavish prismBOT
#

@rustic salmon Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!

Our server rules can be found here: https://pythondiscord.com/pages/rules

ionic raft
#

It's never too late to start

#

I'm working on Whurthy right now. In alpha testing a client helped us realize we're missing a key feature. I'm going back in and adding the ability to have event types. Which offers a completely different track for event management.

quiet cipher
#

interesting

#

good luck :))

ionic raft
#

Yeah. A hair stylist pointed out that they have different types of event and timeblocks. We had missed that as a requirement completely.

#

So yes, software engineering is all about problems. Breaking down the big ones into lots of little ones, and discovering a pile more while you're at it

#

Managed to check to prevent double booking AND cancel timeblocks within the duration of the event type...and then realized a number of things that should be improved...

#

Tomorrow I'll be checking for timeslots that are available for the error message, and hiding events without enough time to be booked for an event type

quiet cipher
#

so far, did any company or professional individual register?

ionic raft
quiet cipher
#

oh great stuff

ionic raft
#

Which is why I love Django. Being able to retrofit this sort of requirement is exactly why I love the framework

quiet cipher
#

yep django is a beautiful framework

#

well im learning it for a school project

#

even though i can use flask i still wanna learn django

ionic raft
ionic raft
# quiet cipher even though i can use flask i still wanna learn django

Django's ORM, admin panel and authentication really make it shine. Plus, it's much more suited to reusability given that you build apps. Flask's flat application layer makes sense for simplicity. But once you've worked out Django's model-forms-views-templates-urls structure it really comes together.

#

And of course, with a sprinkling of settings and admin 🙂

wooden ruin
#

not to mention the django rest framework too!

ionic raft
#

A lot of peeps talk about Django's REST Framework. But when I read about the security risks I'm glad I've spent time digging deep into ORM

ionic raft
#

It's the kind of risk that really should be talked about a lot more. I had to bump into that risk through my own research.

quiet cipher
#

rest api? (maybe its a different thing)

ionic raft
#

However, if you use it access your own DB(s) it comes with...some risks.

wooden ruin
#

the orm escapes all variables when you query them, i think vulnerabilities lie when you directly query the model with raw sql that might cause danger. however drf mostly communicates with the django orm by default so unless you dive deep into the roots, it shouldn't be that much of a security risk

ionic raft
# quiet cipher is it not secure

That's a hard question...and I'm not an expert. Suffice to say, Django's ORM uses parameters to speak to the DB and has built in protection for vectors such as sql injection attacks.

quiet cipher
#

i see

ionic raft
#

The examples they gave weren't just about raw sql.
You can run raw sql with ORM too. But I wouldn't.

#

Never found a DB dance I couldn't do yet with ORM

#

But yes, if you're using the ORM to access the DB you've got built in security

#

Welcome 🙂

#

Also, I find deployed Django projects to be very, very fast

wooden ruin
#

nowadays you almost never need to use raw sql since there are orm's for every database and for many languages

ionic raft
#

I kind of get SQL...but I've had no interest in becoming a SQL expert. ORM lets me off of that chore 😉

wooden ruin
#

the only thing i wish django could implement is a more modular approach. like choosing your own orm, if there was prismajs for python that would be amazing

ionic raft
#

Running PGAdmin for PostgreSQL on my PC was quite a move for me 😄

quiet cipher
#

anyways,
so i successfully setup my django webpage and i got the congratulations page on localhost:8000

next i wanted to create an app
so i created an app called 'pages' (for a homepage)
then i followed the instructions:
first: in views.py

from django.http import HttpResponse
def homePageView(request):
return HttpResponse('Hello, World!')

next: i create a file 'urls.py'

from django.urls import path
from .views import homePageView
urlpatterns = [
path('', homePageView, name='home')
]

then in the main folder (project-level)
i updated the urls.py file

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('pages.urls')),
]
ionic raft
wooden ruin
#

that's cool!

ionic raft
#

So I guess I'm saying that Django native can be architectured in a modular fashion

#

@quiet cipher Looks like progress, bruh 🙂

wooden ruin
#

besides if there's something that you need that django doesn't have out of the box, there's probably a library for that

quiet cipher
#

but i still get the same congrats page

#

:((

quiet cipher
ionic raft
quiet cipher
ionic raft
#

So to display a view you need to import it into urls.py and then use in the pattern

#

Oh I see

#

I'd do urls differently than that

#

I import the views at the top of urls.py

#

then I add the view to the pattern in urls.py

quiet cipher
#

this ?

ionic raft
#

Not quite...sec

unkempt temple
#

I have this django model setup for the backend of my video game ```py
class Player(Model):
pass # other stuff

class SaveSlot(Model):
player = ForeignKey(
Player,
on_delete=CASCADE,
related_name='slots'
)

players can have up to 5 save slots

index = PositiveIntegerField(null=False)

save slot data is stored in a separate table since it contains huge amounts

of data that I do not want to load every time that I read info about slots

class SaveSlotData(Model):
slot = OneToOneField(
SaveSlot,
on_delete=CASCADE,
primary_key=True,
related_name='data',
)

json = JSONField(null=False, default=dict)


When a user creates a new slot, I would like to do this ```py
save_slot = SaveSlot(
  player=player,
  index=params.index,
  data=SaveSlotData(
    json=params.data
  )
)
save_slot.save()
``` but it doesn't work, and the `SaveSlotData` does not ever get created
#

why not?

ionic raft
#

urls.py

urlpatterns = [
    path('', views.home, name='home'),```
unkempt temple
#

also, why doesn't the FK on the OneToOneField prevent this model from persisting?

quiet cipher
#
from django.urls import path
from .views import homePageView

urlpatterns=[
    path('',homePageView, name='home')
]
#

yeah i did this^

ionic raft
quiet cipher
#

yeah i guess

#

i wonder why it doesnt work hm

ionic raft
ionic raft
quiet cipher
ionic raft
#

Not just the first vid

quiet cipher
ionic raft
#

Ok. Good luck all. Off to bed.

quiet cipher
#

good night :))

ionic raft
ionic raft
# unkempt temple bump

To understand why SaveSlotData isn't being saved would need to see the application layer.

unkempt temple
#

huh? why?

#

that second block is nearly identical to what's in my code

ionic raft
# unkempt temple huh? why?

Because logic, at least when I use Django, is what drives CRUD. And I like to have logic in the application layer for the most part. Although, there are different schools of thought about fat data layers

unkempt temple
#

I still don't really see how that's relevant

#

but this is my code exactly

ionic raft
#

I responded that in order for there to be a save, something had to trigger the data event

unkempt temple
#

that line save_slot.create() is not saving the data

ionic raft
unkempt temple
#

.create() is just a shortcut that I made: ```py
class SemanticSaveModel(Model):
class Meta:
abstract = True

def create(self, *args, **kwargs):
    kwargs['force_insert'] = True
    kwargs['force_update'] = False
    return self.save(*args, **kwargs)

def update(self, *args, **kwargs):
    kwargs['force_insert'] = False
    kwargs['force_update'] = True
    return self.save(*args, **kwargs)```
ionic raft
unkempt temple
#

well I had already sent the code snippet above

#

which is the only part involved with record insertion

ionic raft
#

OK. So you're going for a fat data layer...which is cool.

#

That's interesting...I've not seen DB CU done that way before...

unkempt temple
#

by default django's Model::save function will either create or update the record

ionic raft
unkempt temple
#

so forcing a creation or update makes sure that you don't duplicate records

#

this is in a view

#

def save is a view

ionic raft
unkempt temple
#

what?

#

I am doing crud in the views

ionic raft
#

You are calling models class in views.py?

unkempt temple
#

save_slot.create() is the C in CRUD

ionic raft
#

You're putting your data model and doing CRUD in views.py?

#

I put the data model in models.py and application logic in views.py. Separating function from form

unkempt temple
#

I have 3 separate files:

  1. app/models.py which contains my class Player(Model): and others
  2. app/views.py which has def save():
  3. app/urls.py which defines the route to the save view
ionic raft
unkempt temple
#

"save" is the name of the view

ocean slate
#

hey

unkempt temple
#

that might be causing some confusion

ocean slate
#

anyone knows Flask

ionic raft
unkempt temple
#

that's just a shortcut to save

#

like how save itself is a shortcut to raw_save

ionic raft
unkempt temple
#

I call model.create, that function calls model.save

#

thus, create is a shortcut to save

ionic raft
#

The snippet you posted has a Models Class, and includes functional views.

unkempt temple
#

no it doesn't?

unkempt temple
ionic raft
#

class SemanticSaveModel(Model): is a class invoking Models

unkempt temple
#

do you mean subclassing?

#

you invoke methods

ionic raft
#

Never mind...I was off to bed 20 mins ago. Good luck

unkempt temple
#

Model is a class

quiet cipher
#

guys i have an error when im trying to create an app

#
 The included URLconf '<module 'polls.urls' from 'C:\\Users\\Israr Ahmed\\Desktop\\django_SchoolProject\\polls\\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import.
#

error^

#

should i send the code?

dim rover
#

is this for django?

quiet cipher
#

yes django

dim rover
#

can you show that file

quiet cipher
#

ight ill send the code...

#

the project-level urls.py :

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

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

app-level urls.py :

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

views.py file:

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]
#

i am supposed to get this output in the webpage

“Hello, world. You’re at the polls index.”

dim rover
quiet cipher
dim rover
#

you have the same content as in urls.py above

#

it should have the index function

quiet cipher
dim rover
#

yeah

#

its currently a copy of that

dim rover
quiet cipher
dim rover
#

lmao

quiet cipher
#

weird

dim rover
#

i think it tried to import itself

#

from . import views from views py

quiet cipher
#

ahh i tried some stuff but i still get the error

#

but ill keep trying ig

#

nicee now i am getting new error

#
 module 'polls.views' has no attribute 'index'
#

im trying to create an app since like 6 hours 💀

#

im still stuck

dusk portal
#

@inland oak

#

sorry for the ping

#

can i plz get ur 1 min?

#

im unable to serve my static files (rn using nginx)

#

/home/ubuntu/project/sai/media

#

^^ this is my pwd result for

#

media files

#
    alias /home/ubuntu/project/sai/media;
    access_log off;
}
#

im using this inside

#

sudo nano /etc/nginx/sites-available/myproject

#

still not getting media files

#

@ionic raft ^^

rigid mist
#

I wanna execute code in backend ~2 seconds after return statement for Flask template is executed. How can I do that?

atomic sinew
#

I don't understand why my html file is not accessing my static css file.

HTML FILE

{% load static %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Django Begins</title>
    <!-- <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor"
      crossorigin="anonymous"
    /> -->
    <link rel="stylesheet" href="{% static 'css/blog.css' %}" />
  </head>
  <body>
    <header>
      <h1><a href="/">My Django Blog</a></h1>
    </header>

    {% for post in posts %}
    <article>
      <time>published: {{ post.published_date }}</time>
      <h2><a href="">{{ post.title }}</a></h2>
      <p>{{ post.text|linebreaksbr }}</p>
    </article>
    {% endfor %}
  </body>
</html>

lavish prismBOT
#

Hey @atomic sinew!

It looks like you tried to attach file type(s) that we do not allow (.svg). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

Feel free to ask in #community-meta if you think this is a mistake.

atomic sinew
#

Settings File

STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'static'

serene matrix
visual gull
#

hey guys i made an api using FastAPI

#

it can send mock codes

#

it has many modes

#

for ex: alphanum, alphasign, alpha, alphanumsign, num, numsign

#

Code:


from fastapi import FastAPI
import random

app = FastAPI()

ltrs = sorted('qwertyuiopasdfghjklzxcvbnm')
nums = list('123456789')
signs = list('!@#$%*?<>&')
 
@app.get("/{type}")
async def root(type, count: int):
 code = ''
 if type == 'alpha':
     for i in range(count):
         code += random.choice(ltrs)
 
 elif type == 'alphanum':
     for i in range(count):
         code += random.choice(ltrs + nums)
 
 elif type == 'alphanumsign':
     for i in range(count):
         code += random.choice(ltrs + nums + signs)
 
 elif type == 'alphasign':
     for i in range(count):
         code += random.choice(ltrs + signs)

 elif type == 'num':
     for i in range(count):
         code += random.choice(nums)
 
 elif type == 'numsign':
     for i in range(count):
         code += random.choice(nums + signs)
     
 return {'code': code}

Code Editor Used: Spyder
Libraries Used: Random, FastAPI

atomic sinew
daring isle
#
submitChecklistButton(e) {

    const data = {
      'status':'closed',
    }

    axios.patch(`reporting/checklist/${branch_id}/`,data)
      .then((data) => {
        console.log(data);
    })
    .catch((err) => {
      console.log(err);
    })
  }

Anybody know what the syntax error is here?

#

its underlining the first curly bracket {

#

nevermind - it might be this

function submitChecklistButton(e) {

didnt say function

jaunty depot
#

hey guys
is there a way to redirect user to login page after registering?
as with LOGIN_REDIRECT_URL = 'home' redirects you to 'home' view, is it possible to redirect user to login page?

I tried to do it with REGISTER_REDIRECT_URL = 'login' but it does not work, on https://docs.djangoproject.com/ there is also no info about it. Does that mean that it is impossible to make it so?

daring isle
daring isle
#

What you really need to do is make any unauthenticated user get redirected to the login page .

That way it would catch them after reg even if you don’t explicitly say

#
def register_user(request):

    #your register stuff here
    
    return redirect('login')
#

or just try this

#

make sure you import redirect too in your view

from django.shortcuts import redirect
hardy apex
#

anyone have any familiarity with smtp (with gmail) for python?

eager hull
hardy apex
eager hull
#

Sure

hardy apex
#

I have a React Frontend with a form that does a post request on a python backend which sends an email out. however after the email my screen is changed when i would rather just send back an update, would i need a get request here? not sure where to go

#

(images are swapped)

#

here is my python code for all of the backend

#

and my frontend form

eager hull
#

I'm a Django guy, so I'm probably not the best resource for this, but after your email is sent, your are literally returning the word "success". You should replace that with a redirect or a reverse redirect or something,. Ot sure what the react terminology is.

hardy apex
#

So I guess the question is, is there no way to submit a form using post that wont redirect your page?

eager hull
#

If you just use return,won't it leave you on this contact page?

eager hull
#

This might help

daring isle
#

Or something or other . Are you using fetch or axio?

azure pelican
#

What should i know in Python to learn Django

hardy apex
ionic raft
# dusk portal media files

I would not deploy Django to production including the management of Media. It can technically be done, but I won't for two reasons. First, media files are a security vector for malicious files. Second, including media files on a Django web server means it won't be stateless anymore. This will present load balancing issues in the future.

I learned this the hard way when following Corey's tutorial for uploading profile pics. It seems like a good idea, and is for learning about this as a feature. However, using Django to manage media files is not ideal. I'm researching connecting to an S3 server to manage media on another server.

ionic raft
# azure pelican What should i know in Python to learn Django

I got through the basics of Python over a couple of months. Having a solid grasp of lists, dictionaries, variables, logical loops and a grasp of what OOP is will help. Exposure to core Python libraries (dates, math, etc.) will help as well. In short, you need Python to make the application layer really work. You'll use Python to build the data model (Classes), to code the logic into the application layer (CRUD with the DB and sending context dictionaries/variables to the front-end templates), and will work with Jinja2 and html to build the html templates that Django will use to present web pages.

serene prawn
ionic raft
serene prawn
#

It is, also you still can scale vertically to some extent

ionic raft
serene prawn
#

yagni

#

It's a small/personal projects, there's no reason to use something like this, though, for bigger or commercial applications you can use S3

ionic raft
serene prawn
#

Well, they do

#

Should they use s3?

ionic raft
#

IIRC, media can be configured through nginx

#

You can create a media volume along similar lines to serving up static files.

serene prawn
#

Maybe an issue with using alias instead of root? Don't remember which does what but it might be this

ionic raft
#

I used root...

serene prawn
#

Well they use alias 🤔

ionic raft
#
server {
  listen 4000 ssl;
  # # location of SSL certificates
  ssl_certificate /app/web/ssl/ssl.crt;
  ssl_certificate_key /app/web/ssl/ssl.key;

  location / {
    proxy_pass http://django;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_redirect off;
  }

  location /media/ {
    root /app/web/build/media/;
  }

  location /static/ {
    alias /app/web/build/static/;

    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';

        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

        add_header 'Access-Control-Max-Age' 86400;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204; break;
     }

     if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
     }
     if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
     }
  }
}```
#

^ is the original nginx file from a while back. it was working until I deprecated for the project

serene prawn
#

@ionic raft I never had to deal with media files before btw, mainly do some db operations/data processing pithink

ionic raft
#

That was also within a docker container. So, the dockerfile also did some legwork for environment setup (such as building the media directories so the above could work)

serene prawn
#

You use django or some other framework?

ionic raft
serene prawn
#

Don't really like using django for rest apis

ionic raft
#

But I used ngnix to serve static and media.

ionic raft
serene prawn
#

Rest api is interface between server (django) and usually a frontend client (e.g. react)

#

Doesn't have anything to do with db or orm

#

You might have an api that doesn't use db

ionic raft
serene prawn
#

Did you try fastapi or similar frameworks?

ionic raft
# serene prawn Did you try fastapi or similar frameworks?

Not needed to as yet. I tend to focus on techs applicable to problems I have to solve. As yet, I've not had working with REST APIs as a need to solve the problems I've had. I've also stayed away from frontend frameworks like React for now.

#

I'm kind of forcing myself to do as much as I can server-side. That way, it keeps the projects super fast, more secure, and still gets the job done.

serene prawn
#

It's harder to work on frontend this way

#

Since most people use some kind of framework on frontend

ionic raft
# serene prawn It's harder to work on frontend this way

I've not found it hard to work on the frontend. Bootstrap 5 for css framework (because I find vanilla css to be a ghastly language), and every problem I've needed to solve I've been able to do pretty much with Django. There's a bit of JS for things like jquery, Bootstrap and some form field conditional filtering.

#

Oh and htmx for inline forms (partial page refreshing for parent-child forms)

serene prawn
#

It's just kind of better to use rest api's imo because you can separate backend logic from your representation/templates, also it allows you to add more clients in the future (for example a mobile app)

#

And you still can use bootstrap with things like react

ionic raft
#

views.py is my application layer, forms.py controls input and validation, models.py is my backend, and templates are my front end. Seems pretty N-tier to me

#

And app design within the Django project allows me to modularize apps

daring isle
#

im still not sure i can pull off some of the stuff i did in django , its a rabbit hole

ionic raft
serene prawn
#

Depends on how you code them 🙂

ionic raft
daring isle
#

using jinja is a win, jsx is powerful but doesnt seem as efficient

ionic raft
#

What I know is, the projects I build are crazy fast.

serene prawn
#

like yaml

ionic raft
serene prawn
#

My angular projects are fast too, on my machine

daring isle
serene prawn
#

"It works on my machine"

ionic raft
serene prawn
#

For stress/load testing

ionic raft
ionic raft
#

I have an event management app where users can create 1000s of events (through a recurring event creation feature) years into the future. The page displays with pure Django in production is astonishingly fast for me.

serene prawn
#

Aslo rest api's are easier to test imo

ionic raft
#

I will get to React. Just not right now. More Django mastery first

serene prawn
#

django has drf (django rest framework) but i find it outdated compared to fastapi and similar frameworks

daring isle
serene prawn
#

And there's no place for jinja2 sadly

daring isle
ionic raft
#

I've come to really like PostgreSQL as the DB for the backend

serene prawn
serene prawn
ionic raft
#

It's all I these days.

serene prawn
#

I mostly used it with sqlalchemy since it's more flexible than django orm

ionic raft
#

Got an project with 30+ tables. Very complex data model, but it's wicked fast and clients are super happy with the end result.

serene prawn
#

I used django orm too, but it's kind of a nightmare to write a complex query

#

And there's no built-in support for cte's for example

ionic raft
serene prawn
#

Try sqlalchemy 😅

ionic raft
#

The more experience I get with ORM, the more I use it, the easier I find it. That combined with PyCharm has made ORM my beech

#

PyCharm really is wizard for learning ORM

#

Put it this way, I've yet to encounter a query I couldn't build. And once I worked out how it worked I never looked back

serene prawn
#

I don't really like the fact that django orm uses strings for all operations
Imo this is much better:

select(Book).where(Book.title.like("Some Title"))
daring isle
#

from this

#

as an example

serene prawn
#

It depends ofc though

daring isle
#

ohhh no, the data was filtered beforehand!

serene prawn
#

In most cases all you want to do on python side is to transform your data a bit

#

And perform some business logic

daring isle
serene prawn
#

What's wrong with sqlalchemy though?

ionic raft
daring isle
# serene prawn 😦

saying that, sometimes i found myself sat for hours trying to solve issues which raw sql might have been easier

ionic raft
#

Another thing to factor is data model design.

serene prawn
ionic raft
#

My goal is to master Django and dive deep. That's why I'm hesitant to branch out. The main challenge with any language/framework is often, "You don't know what you don't know."

ionic raft
serene prawn
ionic raft
#

I just get the Django ORM. I have a need, design the data model, code the application layer.

serene prawn
#

Depends on orm though

ionic raft
#

On that note...back to coding 🙂

serene prawn
#

There's no much difference between

class Post(db.Model):
    title = models.CharField(max_length=100)

and

class Post(Base):
    __tablename__ = "post"
    
    id = Column(Integer, primary_key=True)
    title = Column(String(100), nullable=False)
hardy apex
#

Please read this and let me know if you have any suggestions

daring isle
#

i cant see it

hardy apex
#

which part

daring isle
#

my eyesight isnt that good

hardy apex
#

i dont want to spam channel, can i DM the snippets zoomed in?

daring isle
#

can you type three backticks then jsx then your code then three back ticks

#
code here
#

` these

#

not \

#

under the esc button

hardy apex
#
import './contact.css'
import {AiOutlineMail} from 'react-icons/ai'
import { useRef } from 'react'

const Contact = () => {

  const nameRef = useRef(null);
  const emailRef = useRef(null);
  const msgRef = useRef(null);

  const handleSubmit = event => {
    event.preventDefault();
    event.target.reset();
  };

  return (
    <section id='contact'>
      <h5>Let's get in touch</h5>
      <h2>Contact Me</h2>
      <div className="container contact__container">
        <div className="contact__options">
          <article className='contact__option'>
            <AiOutlineMail className='contact__icons'></AiOutlineMail>
            <h4>Email</h4>
            <h5>brighamyoung2@gmail.com</h5>
            <a href="mailto:brighamyoung2@gmail.com" target='_blank' rel='noopener noreferrer'>
              Send a message</a>
          </article>
        </div>
        <form onSubmit={handleSubmit} id='passContact' name="passContact" action="." method='post'>
          <input ref={nameRef} type="text" name='name' placeholder='Full Name' required/>
          <input ref={emailRef} name='email' placeholder='Email' required/>
          <textarea ref={msgRef} autocomplete="off" name="message" rows="10" placeholder='Message' required></textarea>
          <button type='submit' className='btn btn-primary'>Send Message</button>
        </form>
      </div>
    </section>
  )
}

export default Contact```
#

this portion has code that will setup a form and on submit will reset the form, however it is not POSTing properly

#

I think the problem is that I am resetting the form before it is done POSTing and I am getting a POST error

#
import './contact.css'
import {AiOutlineMail} from 'react-icons/ai'

const Contact = () => {
  return (
    <section id='contact'>
      <h5>Let's get in touch</h5>
      <h2>Contact Me</h2>
      <div className="container contact__container">
        <div className="contact__options">
          <article className='contact__option'>
            <AiOutlineMail className='contact__icons'></AiOutlineMail>
            <h4>Email</h4>
            <h5></h5>
            <a href="." target='_blank' rel='noopener noreferrer'>
              Send a message</a>
          </article>
        </div>
        <form id='passContact' name="passContact" action="." method='post'>
          <input type="text" name='name' placeholder='Full Name' required/>
          <input type="email" name='email' placeholder='Email' required/>
          <textarea autocomplete="off" name="message" rows="10" placeholder='Message' required></textarea>
          <button type='submit' className='btn btn-primary'>Send Message</button>
        </form>
      </div>
    </section>
  )
}

export default Contact```
#

This section works properly but will not reset my form after submitting and POSTing information

daring isle
#
import { useForm, useState } from "react-hook-form";
import....


  const [formState, setFormState] = useState({})

  
  const { email, handleSubmit, errors } = useForm();

  const onSubmit = (data) => {
    if (data) {
      setFormState(data)
      
    }
form.reset()

  
#

maybe something like this?

#

im still a bit unclear on whats going on tho, are you sending your submission to an api?

#

because you could maybe use async to wait for it to finish

hardy apex
#
import smtplib
from flask import Flask, send_from_directory, request, redirect

#all this information is stored on server under os.environ
# EMAIL_ADDRESS = os.environ.get('EMAIL_USER')
# EMAIL_PASSWORD = os.environ.get('EMAIL_PASS')
# PERSONAL_EMAIL = os.environ.get('PERSONAL_EMAIL')
EMAIL_ADDRESS = ''
SMTP_PASSWORD = ''
PERSONAL_EMAIL = ''

app = Flask(__name__, static_folder='../react-portfolio/build/')

@app.route("/", methods=['post'])
def getValue():
    USER_ADDRESS = request.form['email'] #contact email

    with smtplib.SMTP('smtp.gmail.com', 587) as smtp: #587 is for gmail servers
        smtp.ehlo() #identify connection
        smtp.starttls() #encrypt traffic
        smtp.ehlo() #reidentify encrypted connection
        
        smtp.login(EMAIL_ADDRESS, SMTP_PASSWORD) #login using email and password
        
        contact_name = request.form['name'] #contact name
        contact_message = request.form['message'] #contact message
        
        email_contact = (f'Subject: Contact Form Submission\n\nThank you for sending in your contact information' 
                            f' via . A copy of what you sent is below, thank you!\n\nSincerely,'
                            f'\n\n\n\n[Your Form information]\nName: {contact_name}\nMessage: {contact_message}')
        email_personal = f'Subject: Contact Submission\n\nName: {contact_name}\nEmail: {USER_ADDRESS}\nMessage: {contact_message}'
        
        #smtp.sendmail(SENDER,RECEIVER, msg)
        smtp.sendmail(EMAIL_ADDRESS, USER_ADDRESS, email_contact)
        smtp.sendmail(EMAIL_ADDRESS, PERSONAL_EMAIL, email_personal)
    return ('', 204)

if __name__ == '__main__':
    app.run(use_reloader=True, port=5000, threaded=True)

#

this is what im using for backend

daring isle
#

maybe make your onClick update the form state, have your api useEffect have the formstate as a listener , and have the form clean after the api post in the useEffect

#

im not v good with react atm so im not sure if that will work but worth a try

native tide
#

Hi there, anyone have advance python web development video tutorial share with me

gray shore
#

Hi, i need your help. when i try to install gatsby it gives me this error

zealous elk
#

I am getting an error in a flask website I am working on. The details are in #help-apple, please help me.

astral bramble
#

do you know any good proxy list or api ?

quiet cipher
astral bramble
quiet cipher
#

can you do that with fastapi?

brisk mortar
#

Can you please tell me how to make the same border ?

#

Here's what happened to me

proper hinge
#

For starters you can use css to set a margin/padding.

#

I would probably use flexbox to make this, but that's just cause it's what I am most familiar with.

slate narwhal
#

Hello everyone, does anyone here have experience connecting to MySQL through PHP? I'm having trouble connecting on my Mac and I'm looking for some guidance.

ionic raft
ionic raft
# brisk mortar Here's what happened to me

You could also use a css framework such as Bootstrap (or Tailwinds). Bootstrap would allow you to fairly easily set padding and borders. Plus, Bootstrap offers an easy way to build grids (based on flex in vanilla css).

brisk mortar
ionic raft
# native tide Hi there, anyone have advance python web development video tutorial share with m...

I got started with Flask and then Django (the main Python web development frameworks). I would advise starting with Flask unless you're VERY familiar with back-end web development. I recommend Corey Schafer's tutorials.
Flask: https://www.youtube.com/watch?v=MwZwr5Tvyxo&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH

In this Python Flask Tutorial, we will be learning how to get started using the Flask framework. We will install the necessary packages and get a basic Hello World Application running in our browser. Let's get started...

The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Flask_Blog

Djang...

▶ Play video
ionic raft
brisk mortar
ionic raft
ionic raft
# brisk mortar I signed up for a special course

If you're trying to replicate the border on another website and can inspect the page source, then you can reverse engineer.
If you're looking for help here you'll need to share your html and css code snippets.

ionic raft
brisk mortar
ionic raft
#

This discord won't solve problems for you. We will try and point you towards directions that with some research and application will support you in solving the problem yourself

ionic raft
# brisk mortar And there is

So when you look at the html and css so far, have you been shown how to build borders around elements on a page?

brisk mortar
ionic raft
ionic raft
brisk mortar
ionic raft
ionic raft
brisk mortar
#

Okay, I understand you. Thanks

ionic raft
# brisk mortar Okay, I understand you. Thanks

I do get the urge to ask someone else to solve the problem for you. However, by pointing you in the right direction and not showing you the solution you get to refine the most useful skill in software development...

...problem solving 😄

ionic raft
#

I just spent four days on a logic problem...there comes a point in software development where it's less about research and more about breaking down the problem effectively and building the right logic. For four days I had an assumption in a query that meant it would never work. I don't see it as four long days now, rather, as four days to learn an important lesson about queries and what you include or exclude from the query.

#

Four days to get this error message working correctly...

#

It turns out, having a list of services (or event types), a bunch of timeslots to book within, and ensuring that customers don't double book, while you automate conditional discounting is quite tricky 😄 but accomplished in 68 lines of Python 😉 And I'm sure it could be refactored to be quicker...but not today 😄

#

In this case, the customer can either book for themselves, or staff can book for the customer. Lots of FUN 😄

native tide
#

Please recommend me a tutorial series or something to learn how to fill forms and retrieve data or basically web scrape but without using something heavy like selenium.

My goal rn is to login to https://zoro.tutoreva.com/ and then retrieve the current updates. I did make it possible using selenium but it was not worth it at all. Someone in the server before recommended me that it can be done using requests or urllib only since the thing is just a form but being a complete beginners, I need to learn it from scratch and self-teaching via docs was tough.

ionic raft
native tide
ionic raft
native tide
ionic raft
native tide
#

Alright

ionic raft
#

It's also late in North America. Come back tomorrow.

native tide
#

Ah, good idea.

inland oak
inland oak
#

Availability of non selenium solutions depends on the site

#

Its components should not be rendered through JavaScript.
So non selenium solutions aren't usually available to modern solutions like React/Vue/Angular

#

Regular web sites, which are build with just html/CSS are perfectly scrapable without selenium.
As example sites built in Django or other backend Frameworks directly
As long as Dev did not use js for more dynamic stuff

#

Web scraping without site owner permissions is highly unethical also, and in some countries against the law
(Because the web site owner wastes additional electricity / CPU / memory / ram and eventually extra money just to accommodate your inhuman bot actions which were not intended for site to be used in its ToS.
A single bot could be consuming web site owner's money intended to accommodate thousands of regular users)

somber plover
#

It's probably worth pointing out the difference here between badly behaved resource hogging web scraping vs. occasional and lightweight scraping (e.g. many moons ago before there were library book reminders, I wrote a python scraper to do a once-a-day overnight job to check library due dates).

#

The latter kind of scraper poses no ethical problems.

inland oak
# somber plover It's probably worth pointing out the difference here between badly behaved resou...

Judge Dredd is a 1995 American science fiction action film directed by Danny Cannon, and starring Sylvester Stallone, Diane Lane, Rob Schneider, Armand Assante, and Max von Sydow. The film is based on the strip of the same name in the British comic 2000 AD.
Dredd trailer 2012 Dredd 2012 Trailer is a British science fiction film directed by Pete ...

▶ Play video
native tide
#

Well, TutorEva app is also available in PlayStore or AppStore if you are from the US so the link is safe but your choice.

#

I think the website does not have any sort of JavaScript. Maybe pure HTML and CSS.

inland oak
#

And all the removed complexity by using python instead of SQL

#

U don't want to know how the code is messy in apps who don't use it. It is just pure horror from ancient times.

#

In the right clean architecture, and with usage of stuff like flyway, we can afford using not ORMs I think, but those are things much less known, more demanding to skills

serene prawn
astral ledge
#

hey guys, i have a generics.createAPIView in django. It works as intended, but how do i make it give PK of the new object in the success response

serene prawn
astral ledge
#

not sure, I have added fields all to my serializer

#

but PK field is not there

serene prawn
#

It's probably id and not pk

astral ledge
#

it seems to work actually if I pass in fields

#

all only returns the editable fields i guess

serene prawn
#

Hm, no, it should return all fields 🤔

inland oak
sudden sierra
astral ledge
#

ye i just fucked up with fields, works fine now 🙂

native tide
#

so im making an android app which will communicate with django backend thru a REST api, I need to login users and keep track if they are logged in like django does on web app, now ik django uses a cookie based session system to check logged in users, my question is should i use the same for app as well or go with alternatives like JWT? which one is better in general

distant panther
#

i am working in flask-socketio and getting a error io is not defined

#
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">
    <script defer src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    <script defer src="socket.io/socket.io.js"></script>
    <script defer src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <title>Website</title>
  </head>
  <body>
    <div class="container">
      <div class="messages">
        <div class="msg">Hello There! My name is Steven</div>
      </div>
      <form>
        <input type="text">
        <button type="button" name="button">Send</button>
      </form>
    </div>
  </body>
  <script type="text/javascript" charset="utf-8">
      var socket = io();
      name = prompt("Enter your Name!!")

      socket.on('connect', function(name) {
        console.log(`${name} Joined the Chat!`)
        // socket.emit('joined_', name=name});
      });
  </script>
</html>
#

code

molten comet
#

Are there any resources on how to learn full stack web development with python, like videos or a website or anything? Preferably free obvious but I'd take any information you guys have.

quiet cipher
#

But its not very detailed

#

But its worth a shot

round shard
#

I have my main.py that is the file that I run. Is there something like discord.py cogs that lets you open routes in another file so that -->

main.py ```py
@app.route("/main")

extra_route.py ```py
@app.route("/extra")

and extra also runs? I can reformulate

daring isle
#
import Dialog from '@mui/material/Dialog';
import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
import React from 'react'
import { createContext } from "react";

function PopUp(props) {
   
    const PopUpContext = createContext(null);
    const{title, children, openPopup, setOpenPopup} = {...props};


  return (
    <PopUpContext.Provider value={props.openChecklist}>
        
    <Dialog open={openPopup} >
        <DialogTitle>
            {title}
            </DialogTitle>
            <DialogContent>
                {props.children}
                
            </DialogContent>
        
    </Dialog>
    </PopUpContext.Provider>
  )
}

export default PopUp

Im trying to pass data to a children form in a modal.
im doing something wrong because the form component cant find the context.

#

any ideas

molten comet
#

well i know python a bit, and I have used html, css and JS before, although JS knowledge isnt really too great, and I would like to use django as the backend with sqlite or smth else as the database, I guess I am looking for smth where i get some infos about JS and django

#

And i guess how you bring the backend and the frontend together exaclty

daring isle
#

pure django is pretty good. Theres a bnging tutorial by codemy on youtube to get you started

soft nacelle
#

h

daring isle
#

or this one is a pretty decent Rest API / React Video. Its pretty long tho

frank shoal
#

react, boo! vue, yay!

molten comet
#

okay thanks! I will look into those

daring isle
#
const handleSubmit = () => {
   
        
        (!props.checkList ? 
            async function postReport() {
                const request = await axios.post(`reporting/checklist/`,values)
        console.log(request.data);        
        forceUpdate();
        return request
        .then(console.log('posted'))
        
        }
        
        : (
            async function putReport() {
                const request = await axios.put(`reporting/checklist/${props.checkList.id}`,values)
            console.log(request.data);        
            forceUpdate();
            return request
            .then(console.log(`putted ID: ${props.checkList.id}`))
                }
            )
        )
          .then((res) => {
            console.log(res);
            
                  
        })
        .catch((err) => {
          console.log('Error Response')
          console.log(err.response)
          console.log('Data package')
          console.log(values);
          
        })
  
  
      
      handleClose()
  
  
  
    };

Can somebody check my syntax

#

getting this error

#

im trying to post if theres no object and put if there is

rustic wigeon
#

Your .then is literally hanging off of an else statement - i suggest you use if statements more rather than ternary operators, makes the code a lot cleaner:

const handleSubmit = () => {
  if (!props.checkList) {
      async function postReport() {
      const request = await axios.post(`reporting/checklist/`,values)
      console.log(request.data);
      forceUpdate();
      // something like .then(() => console.log("posted")) is better anyway
      // and EITHER RETURN the request or LOG IT. not both.
      return request
      .then(console.log('posted'))
        
    }
  } else {
    async function putReport() {
        const request = await axios.put(`reporting/checklist/${props.checkList.id}`,values)
      console.log(request.data);
      forceUpdate();
      // don't do this... either console.log the request or return it!
      return request.then(console.log(`putted ID: ${props.checkList.id}`))
    }
    // what goes here?
    .then((res) => {
        console.log(res);              
    })
    .catch((err) => {
      console.log('Error Response')
      console.log(err.response)
      console.log('Data package')
      console.log(values);  
    })

    handleClose()
};
#

@daring isle

daring isle
#

all the logs is just so i can debug

daring isle
daring isle
daring isle
# rustic wigeon <@752600622926397571>
const handleSubmit = () => {
   
        try {
        if (!props.checkList) {
            console.log('New Report')
            async function postReport() {
                console.log("Posting")
                console.log(values)
                const request = await axios.post(`reporting/checklist/`,values);
                console.log(request.data);
                console.log("Posted")
                handlePopUpClose(false);        
                props.forceUpdate()
                return request
                
                        
                };
        postReport();
    }
        
        else {
            console.log('Existing Report')
            async function putReport() {
                console.log("Putting")
                const request = await axios.put(`reporting/checklist/${props.checkList.id}`,values);
                console.log(request.data); 
                console.log("Putted")
                handlePopUpClose(false);        
                props.forceUpdate();
                return request;
                
                };
        putReport();
    }      
}
catch (err) {
    console.log(err.response);
    };
    
};

Finally got it working. Thanks for the help dude you really pointed me in the right direction

#

ill change the console logs to loading gifs or something.
and that catch err is prob redundant but idk. it kept saying not in stack before i got it working

wooden ruin
#

where's a good place to learn about the microservice architecture?

dusk totem
#

Is Django framework named after a Belgarian-born jazz player? I got curious as to why its called Django.

proper hinge
#

Belgian, but yes it is.

honest oxide
#

Why people don't like horizontal scrolls? they are actually really cool

dusk totem
#

Unless the site treats vertical scrolls as horizontal events, sure

wooden ruin
native tide
#
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

app.run(host='0.0.0.0', port=81)```

i am having problem in rendering index.html
obtuse robin
#

is it in a templates folder

plucky wadi
#

How do i serve media files in django in production (i'm using nginx as my web server and gunicorn as my application server ) whitenoise works for static files , but not for media files.

outer vortex
late gale
#

can someone help me here

@api_view(['POST'])
def user_update(request,pk):
    if request.method == "POST":
        user = User.objects.get(pk=pk)
        try:
            user_p = UserProfile.objects.get(user=user)
        except:
            user_p = UserProfile.objects.create(user=user)

        serializer = UserUpdateSerializer(instance = user_p , data = request.data)

        if serializer.is_valid():
            serializer.save()

        return Response(serializer.data)

I'm trying to update user profile but im getting an error
"UserProfile.user" must be a "User" instance.

#

oh fixed it ty

native tide
late gale
#
@api_view(['POST'])
def user_update(request,pk):
    if request.method == "POST":
        user = User.objects.get(pk=pk)
        
        try:
            user_p = UserProfile.objects.get(user=user)
        except:
            user_p = UserProfile.objects.create(user=user)
        
        serializer1 = UserSerializer(instance = user , data = request.data)

        serializer2 = UserProfileSerializer(instance = user_p , data = request.data)

        if serializer1.is_valid() and serializer2.is_valid():
            serializer1.save()
            serializer2.save()

        Serializer_list = [serializer1.data, serializer2.data]
        

        return Response(Serializer_list)

Why don't the serializers save the data

#
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'email']


class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = '__all__'
late gale
#

here's my console

Method Not Allowed: /api/user/update/1
[14/Jun/2022 17:11:14] "GET /api/user/update/1 HTTP/1.1" 405 5631
[14/Jun/2022 17:11:16] "POST /api/user/update/1 HTTP/1.1" 200 5811
late gale
#

I printed out the serializer1.validated_data and got the data but when I printed out serializer2.validated_data I got an empty braces

#

found an error
The submitted data was not a file. Check the encoding type on the form.

#
{
    "id": 1,
    "username": "user4",
    "email": "email2@gmail.com",
    "image": "/media/default.png"
}

That's the json Im giving

charred cedar
#

what language mode do you guys use when writing flask/django templates?
it seems i can only have emmet shortcuts OR have jinja shortcuts.

thorny quartz
#

is it possible to get data on popup without ajax but using javascript in django

sudden sierra
ionic raft
ionic raft
ionic raft
# honest oxide Why people don't like horizontal scrolls? they are actually really cool

In a webpage? I wouldn't use horizontal scroll (99% of the time) because of UX. You lose design coherence, interrupt the flow of information, and inconvenience the user to scroll. Plus, if your page width already leads to a horizontal flow I can only imagine what the mobile responsive view is like.

Now I'm not saying there is never a use case for horizontal flow. But I cannot think of an instance in any web project I've coded where it struck me as something required or that would enhance the user experience. But then, I guess I'm fussy about creating web applications that place a premium on the UX.

ionic raft
thorny quartz
golden bone
ionic raft
#

I've pulled off some pretty funky presentation tricks with jinja. Solid AF

golden bone
thorny quartz
#

basically means better than django templates

#

tags

ionic raft
golden bone
viscid valley
#

The new Django 4.0 seems a huge mess. My urls.py don't seem to work, just the entry one for the project. Any way to remedy this?

charred cedar
ionic raft
ionic raft
paper yacht
ionic raft
#

I've got a couple of projects on the go for Django==4.0.4. All good here

viscid valley
#

Worked fine <4.0 seems

ionic raft
viscid valley
#

How do you include them?

#

thanks for the help btw.

ionic raft
#

Then I'd check that the views are calling the correct templates and are imported into the patterns

thorny quartz
viscid valley
#

I mean, a simple import of urls from each?

#

This wasn't required before.

ionic raft
thorny quartz
viscid valley
paper yacht
ionic raft
viscid valley
#

I'm happy for you though, if you're not going to contribute to the discussion no need to chime in thank you though.

viscid valley
thorny quartz
#

everything is there

ionic raft
#

The ROOT_URLCONF = in settings.py will identify the project's urls.py file. The includes will add each app's url patterns into the search

viscid valley
ionic raft
#

That structure was as true for 3.6 as it is for 4.0 🙂 Good luck

viscid valley
#

Thanks man, my project is quite out, got a lot of tinkering to do! A lot worked that suddenly doesn't. Thank you for the help!

#

Working fine by the way.

thorny quartz
#

@ionic raft jinja looks same as django tags

ionic raft
#

Yah. Basically, the project's urls.py will be used for the build of all routes. The includes will bring all urls from all apps in. When you add an app, you want to add the include to the project's urls.py file to your to-do list for configuring the app

ionic raft
thorny quartz
#

But whats the point then ?

ionic raft
thorny quartz
#

I mean what’s the benifit ?

#

Benefit

ionic raft
viscid valley
#

How are urls with regex handled now?

#

I see url has changed to path.

steel delta
#

Can we ask for help or guide here?

thorny quartz
#

Ok one more thing can i get data in popup box in django template without ajax but using javascript

ionic raft
#

As a rule of thumb, I start with documentation and find the answers I need 80% of the time. Then I come here

#

Actually, I go to Stack Overflow 2nd...THEN come here 😄

#

Plus, by referring to the docs you bypass bad advice...which happens

ionic raft
thorny quartz
#

Always remember google is your best friend

ionic raft
#

I'll include the words "stack overflow" in my searches for code issues

ionic raft
#

pop ups have been abused by scammers and have come to make my teeth ache

steel delta
#

Any guide on how do I pass an integer value into foreign key value, I keep getting value error of instance, thanks!

thorny quartz
#

Is htmx is useful ?

#

To use in template ?

ionic raft
steel delta
ionic raft
#

I've been making HUGE use of htmx for inline forms (Parent and child in same form). AMAZING to have ajax without having ajax. Very dynamic and fast!

ionic raft
# steel delta

You need to store the object, not the id. Are you following?

thorny quartz
#

Can you give any docs or something so i can learn ?

ionic raft
# steel delta

Basically, it looks like you're sending the id attribute. Go one level higher and pass the object.

steel delta
ionic raft
ionic raft
steel delta
#

Thanks for the guide!😁

ionic raft
# steel delta I need to like reference the the integer to the id

It helps to think like a DB. The FK from the ORM's perspective is actually a link to the related instance (the record on the other table). You'll be glad of this in the long run because by accessing the reference you can get at all the FK's attributes through a query directly.

#

If you need the id/pk then you call on the .id attribute.

#

And to think, I only started with Django last July. Amazing how much i've learned in close to a year 😄

thorny quartz
#

Bro give me any best link or docs something to learn htmx please

ionic raft
thorny quartz
#

Ok

ionic raft
#

I watched what they did, then adapted.

#

Setting up htmx to replace inline forms is a bit tricky at first. But it's amazing when you get it working. Django's inlineformfactories are kind of arse TBH

thorny quartz
#

Thanks bro 😊

ionic raft
# thorny quartz Thanks bro 😊

Good luck. I've got 3 projects with htmx in them. I keep the base htmx script in my base.py file for all projects. Wouldn't build a Django app without htmx now 😄

viscid valley
#

With urls.py urls aren't without / what's the proper regex to remedy this?

ionic raft
viscid valley
ionic raft
viscid valley
#

Crazy static files show up in brave, but not chrome or firefox.

#

Says not found 404.

#

but appears fine in brave.

#

Oh turns out all static is foobar oopps

blazing sage
#

how do I scroll down a table in selenium?

viscid valley
#

@blazing sage ```py
element = driver.find_element_by_id('some_id')
element.location_once_scrolled_into_view

#

Can also inject js

blazing sage
#

but I also have another problem

#

When I use headless for selenium it won't return any info. What do I do?

slate narwhal
#

Hello everyone, I'm just looking for some guidance here
I'm trying to create a website, when a button is pressed I want to pull information from a database and display it on the users screen.
How would I make the button pull information from the database after it is clicked?
I already have my PHP connected to a MYSQL database

ionic raft
wind dove
#

I need opinions, does that look like it's a scam? Obviously I know it's not since I made it but do you think your average user would be sketched out by that?
I will make the css better eventually but it might end up like this on the initial release

proper hinge
#

The styling of the buttons is too tacky for my tastes. I think it would look more legit if you used the logo of the service. That's what most websites do. Some examples:

#

These are sign ins but a pairing function would also fall under a similar style I think

wind dove
wind dove
#

Just going to mess with the size of the images probably

#

and possibly the font

proper hinge
#

Yeah it's a good start.

proper hinge
#

It's very out of place

wind dove
#

Yeah true ty :D

#

I prefer backend lol

proper hinge
#

Me too.

#

I tend to just make something decent, but uninspired/generic. Typically relying on default styling of the frontend framework

wind dove
# proper hinge I tend to just make something decent, but uninspired/generic. Typically relying ...

You see, when I started this project about a month ago I challenged myself to do it with bare css because I wanted to learn at least the basics, now I'm strongly regretting it but trying to implement a framework now will either a.) require me redoing all of the styling (which sounds like hell) or b.) just randomly start using it which would make the stylings not match too well and also just code wise a horrorshow

#

Goddamn I forgot how to write in english while typing that at first lol.

#

Then again, with how I'm writing my css it's already a horror show lol

proper hinge
#

Doing it from scratch certainly is a challenge, and can be fun in some sense. But it doesn't result in nearly as much productivity. I am perhaps one of the few people who likes CSS but I admit it has its fair share of confusing and frustrating things.

#

At least you learn a lot, I hope.

wind dove
wind dove
proper hinge
#

In an introductory course in uni we were given an HTML file and had to style it without changing the HTML. I went really far and learned a lot of relatively advanced things like using psuedo elements. It's surprising how far you can get with just CSS.

wind dove
dusk sonnet
#

Hi, how can i force a element's scrollbar to always be at the bottom everytime the page is loaded?

obtuse robin
#

but don’t change the ones that are already smaller than the about me box

obtuse robin
obtuse robin
#

i’m not quite sure what you mean though

dusk sonnet
obtuse robin
#

how long is the div? is it a constant value or a percentage

dusk sonnet
#

vh

obtuse robin
#

oh i see

#

you can probably make a vh to pixel converter in javascript

#

and using that

#

move the page down that much when it’s automatically loaded

dusk sonnet
#

i dont know what that is lol

#

or how to even do that

obtuse robin
#

or

#

grab the length of the div instead of converting

#

and move the scroll bar down that way

dusk sonnet
#

Iv tried doing something like this but it doesnt work

const bottom_scroll = (node) => {
    node.scrollTop = node.scrollHeight
}
#

it only works if you do a hard reload/refresh of the page lol

obtuse robin
#

could it work if you specifically refresh the div

#

?

#

or do you also not want thst

dusk sonnet
#

na

obtuse robin
#

hm i see

dusk sonnet
#

i thought u were asking if my current method works

obtuse robin
#

instead of refreshing the page, you can refresh specific parts of a page

dusk sonnet
#

because if its not at the bottom the user will first see the older messages rather than the most recent

obtuse robin
#

what are you making?

#

a chat app

dusk sonnet
#

ye

#

pretty much almost done just tweaking things

timber jungle
dusk sonnet
#

anyone know if developer tools affect functionality? i have a function where window.onload = scroll to bottom of div however this function only works if the developer tools are opened. If they are not opened the function doesnt work.

#

its so odd

daring isle
#

using React/Django : wheres the best place to make API calls for user info?
I have them in a home page component atm, but i'll need user data across the app.

Should i be just making my calls from Index?

#

This is likely v opinion based

wind dove
#

And the School one will be changed too, though I don't know how I'm going to implement that yet as I don't want users being able to type a random school. I'll probably do some school email authentication or something

viscid valley
#

After spending days upgrading to Django 4.0 nothing seems to work. Especially path(r'auth/', include('accounts.urls')), Nothing from auth seems to work. Any way to remedy this? Perhaps a working example.

wind dove
wind dove
wind dove
viscid valley
viscid valley
#

Current urls.py ```py
urlpatterns = [
path(r'', Index.as_view(), name='index'),
path(r'grappelli', include('grappelli.urls')), # grappelli URLS
path(r'ckeditor', include('ckeditor_uploader.urls')),
path('admin/', admin.site.urls),
path(r'auth/', include('accounts.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path(r'^payment/', include('payment.urls')),
path(r'^tracking/', include('tracking.urls')),
path(r'^', include('main.urls')),

# Main App Include
path('', include('main.urls')),
# Auth

]``` excuse the mess

#

@wind dove

wind dove
#

Just another thing I saw, I forget which order it reads it but wouldn't one of these not work?

    path(r'', Index.as_view(), name='index'),
    path('', include('main.urls')),

Could be wrong as your urls.py is more complex than any I've used before

viscid valley
#

the url I'm trying is

wind dove
#

Could you send the accounts.urls?

viscid valley
#

Switching from url without use of regex to path has really killed me dude.

wind dove
#

Oh wait, I understand how that works now, one is an include one is just a single page.

viscid valley
#

It just werks.

#

Ah ok, one is a view, one is just including another urls.py

wind dove
#

if it was the other way around it wouldn't work though lol

#

I think

#

Yeah, could you send the accounts.urls?

viscid valley
#
from django.urls import path
from accounts.views import *

from accounts.views import AuthLogin
from django.urls import path, re_path

urlpatterns = [
    re_path(r'^log_in/$', AuthLogin.as_view(), name='log_in'),
    path(r'^sign_up/$', SignUp.as_view(), name='sign_up'),
    path(r'^activate/(?P<key>.+)$', Activate, name='activate'),

    path(r'^premium/$', Premium_check.as_view(), name='premium_check'),

    path(r'^log_out/$', auth_logout, name='log_out'),

    path(r'^pass_recovery/$', PasswordRecovery.as_view(), name='pass_recovery'),
    path(r'^pass_reset/(?P<key>.+)$', PasswordReset.as_view(), name='pass_reset'),

]
#

Thanks a lot for the help bro

#

Oh, no regex, fixed

wind dove
#

Is it working? If not, I apologize as I don't think im going to be of much help

viscid valley
#

Well, it's using path.

#

but contains regex, so I simply used re_path instead.

wind dove
#

Oh

viscid valley
#

url supported regex

#

Path doesn't

#

As far as I know.

wind dove
#

Yeah, I don't think I can really help as I have always put off learning regex and this is too confusing for me now lol

viscid valley
#

Oh, go learn some LISP.

#

It was one of my first languages I'm really fond of it, but kids these days aren't. Don't blame em.

wind dove
#

c family as in c/c++, and lightly on c#.

viscid valley
#

What're you doing in all of them?

#

I've been using C# since it came out, been using it to make crappy Unity games. Took a stance to stop gaming and spend time creating them instead. Curious how long I'll last. Elden Ring is looking pretty juicy!

craggy flax
#

import numpy as np

def keygen(chaos_func, length, *args):
xn = chaos_map(chaos_func, length, args)
key = np.around(xn
1e9) % 256
return key.astype(int)

def chaos_map(func, length, x0, *args, **kwargs):

generated_map = [x0]

x_n = x0

for i in range(length):
    x_next = func(x_n, *args)
    generated_map.append(x_next)
    x_n = x_next
    
return np.array(generated_map[:-1])

def diffuse(key, image, inv=False):
ciphertext = np.bitwise_xor(key, image.flatten()) % 256
return ciphertext

def encrypt(image, key, iterations=1):
confused = arnold_cat(image, iterations)
ciphertext = np.bitwise_xor(key, confused.flatten()) % 256
return ciphertext.reshape(image.shape)

def arnold_cat(img, iterations=1, inv=False):
try:
image = img.clone()
except AttributeError:
image = img.copy()

N = image.shape[0]
x,y = np.meshgrid(range(N), range(N))
xmap = (2*x+y) % N
ymap = (x+y) % N

if inv:
    xmap = (2*x-y) % N
    ymap = (-x+y) % N
    
for i in range(iterations):
    image = image[xmap, ymap]
    
return image

def decrypt(ciphertext, key, iterations=1):
inv_diffusion = np.bitwise_xor(ciphertext.flatten(), key) % 256
recovered = arnold_cat(inv_diffusion.reshape(ciphertext.shape), iterations, inv=True)
return recovered

def improved_sine(x, alpha):
assert 2 < alpha
coeff = (alpha-2) / (alpha * (1 - np.sin(np.pi/alpha) ) )
const = (alpha-1) / alpha
return coeff * (np.sin(np.pi*x) - 1) + const

def sine_map(x, sigma):
return sigma * np.sin(np.pi * x)

def logistic_map(x, r):
return r * x * (1-x)

#

Can anyone tell me how this code works please

ionic raft
ionic raft
native tide
#

anyone can help with parsing args in py flask?

native tide
#

i made this todo list for my future

golden bone
# native tide i made this todo list for my future

Don't feel like you need to master all those things before you can get an engineering job. If you can complete one decent and original project in Django or even Flask or FastAPI, it's not implausible to get a job