#web-development
2 messages · Page 231 of 1
I think it will work bcus my whole config and app was built for heroku, so PostgreSQL will have the "exact" DATABASE_URI
yep, I'm also thinking in this way
Hello guys,
I have a problem with updating json fields in flask sqlalchemy. Does anyone have any idea how to solve it. Thanks!
I don't have XP with flask sqlachemy but can try. Can you post more context?
@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```
and now what is the error you get?
@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 ''
I mean, when you're running the code, do you get any error in your terminal?
There is no error
So the problem is that json field is not updating?
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.
and it is in this updated_values that this should happen?
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.
yeah, this time I won't be able to help 😕 don't have much experience in the sqlalchemy world (it's in my list to study btw)
@novel stream no problem mate 🙂
I am still learning also, thanks anyway.
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
What change specifically are you trying to do
I created a superuser which seems to have every permission, Id like it to only have access to a few permissions
Adding, changing, removing and viewing the models Game and Song
You can remove its permissions in the Django admin area, removing the flag is super user as well as the permissions that you want. But I'd advise to have at least one superuser and another user with lower permissions
How do I remove a permission though
I can see the list of permissions but I can only seem to select them, no option to delete or change
Unless the orange selection is supposed to be how I pick permissions? If so thats very unintuitive
A superuser normally won't need the permissions unless you explicitly use them in your views. Otherwise even tho it doesn't show any permissions in the right side, it will have access to pretty much everything
Alright I think I got it thanks
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
yeah it works perfectly fine
Not so sure how to use this, is this incorporated with my IDE (pycharm) or is it an app to install?
CI/CF available through GitHub as 'Actions" but for a simple app you might not need it. PyCharm can help you connect the remote repo and push and that may be all you need
Will pushing add or replace the code?
The changes in your local repo will be pushed to the repo on GitHub.
So itll create a copy of the repo at first then any additons or subtractions will replace that code
I see
Basically I guess. I wouldn't say "replaced" because you can always check out earlier commits... It's worth reading up thoroughly on how versioning works because it can get confusing
thanks
Can anyone help me with flask, docker?
ask your question.
Everything works fine, image is created but when I run the container it immediately stops
Should I call you or its fine here?
here is fine.
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
Both should work in theory. Use docker logs to see why the container is stopping
Hopefully it will be still fine. My web app runs but docker somehow fuckd up. Im gonna have an internship interview tomorrow.
how are you running the docker image?
you mean the command?
yes
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"
Does anyone have any experience with implementing Premium TinyMCE features in Django?
is there a way to hook up a domain with flask directly?
Hey guys, Is there a way to get the name of the uploaded file in django?
hey i need some help in my django project
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!
I believe that you would just point an a record to the ip of the flask server. With that, iirc you should be going through something such as an apache server for security reasons.
Like this newinstance.uplodedfile.name
The file name is stored in name attribute
I was just typing that 😆 that should work
Lol
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?
Not from scratch, django automatically generate sqlite database when it's not found, if you delete it you just want to migrate not make migration
There is the flush command but it doesn't clear the tables created from the migrations https://docs.djangoproject.com/en/4.0/ref/django-admin/#flush so the best way is like @mystic wyvern said: delete this file and re-run the migrate command when you're done. Django will recreate the file
but i will be changing my models so i would need to makemigrations first right? or its not needed?
In this case yep you should
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?
@mystic wyvern@novel streamalright thank you sirs
A few days ago I was reading a SO answer that was talking about that. it might be useful for you https://stackoverflow.com/a/39476404/3716354
thank you that's perfect!
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
you need to install the module
try to find it in pip
can you sebd
the code
pls
for the pip
install
webengie
engine
look up the module name in pip
oj
or look up the error in google
ty
Figured this out?
Hello. I'd like to share a Django package I created. Is that allowed ?
nope i gave up on it
cant find anything online on it as well
I guess so
https://pypi.org/project/drf-admin/
Please check it out. I'd love contributions
what does tornado offer that would make anyone pick it over flask or fastapi for small APIs
Is Wordpress worth learning
Best web dev road map for noobie?
If you want to build a simple web site yep it is
Can you tell more details what you want to do
How do I do an inner join in django?
I believe that you can use select_related() in query statement ex:Model.objects.select_related('yourfield1', 'yourfield2', etc.. ) there is a different way but this is the simplest way
oh
Uh, by pressing enter? Or am I not understanding the question?
Probably they meant text wrapping
I'm not sure
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)
Does anyone have experience with setting up JWT Authentication in Django? I'm trying to connect with an external API that needs JWT Auth.
in flask is it possible to define routes in a module and import them into the main module?
Yes i do, what is your Problem
Inexperience with JWT Auth basically. I'm trying to connect to Tiny Drive. Their documentation has PHP covered but nothing on Django.
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
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?
I am not clear on this. Tiny Drive requires jwt Auth to access. Their documentation has an example for PHP. The django-tinymce library is third party and has nothing for premium features.
I've been trying to follow this. I have the key pair built through their app: https://www.tiny.cloud/docs/tinymce/6/tinydrive-jwt-authentication/
Guide on how to setup JWT Authentication for Tiny Drive
This comes back to my inexperience with JWT auth in Django. It appears that I need to setup a JWT endpoint. This apparently allows Tiny Drive to work.
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.
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
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!
Interesting. On the plus side, Tiny have gotten back to me. I think they've realized there's no support for Django and may be looking into it.
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.
I think Flask is a good start to create a website. It has fewer features than e.g. Django so it's easier to get started I'd say.
I am not too familiar with netlify but I thought it was for hosting static sites. As for React, that's a front-end framework only. You can do a combination like React frontend + Flask backend if you wish, but that's a more complicated architecture so I wouldn't recommend it if you're just trying to build your first website.
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
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?
https://www.pythonanywhere.com/ I've heard of too
Host, run, and code Python in the cloud: PythonAnywhere
Ah great, thatnks!
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
G'day guys, I'm working on a python project that pulls weather data from BOM (https://bom.gov.au).
The script works correctly, however I would like for it to be able to use part of the URL within the
register and login /logout is not work
User has no customer.
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
)
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
There is another method that dosent belong to channel, is to use signals like user_logged_in there a good answers here https://stackoverflow.com/questions/29663777/how-to-check-whether-a-user-is-online-in-django-template
fair enough that sounds pretty good ill see what i can do.
ok ill check it out as well
is there a way to verify the django superuser email when created?
try to open admin panel and check?
the superuser email doesn't appear on Email Addresses and I have to manually add that, I'm using dj-rest-auth so for normal user it's kinda easy for admin idk how I can make that happen
I had tried this way, but it doesn't show the columns of the other table, it only shows the columns of a Model
See the second answer that worked for me https://stackoverflow.com/questions/48128714/how-to-make-an-inner-join-in-django
I want to show in an Html the name of the city, state, and country of a publication. But they are in different tables.
Here is my models.py
class country(models.Model):
country_name = models.
Help me
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.
I still think the best way to extend the user model is following one of the approaches demonstrated here https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html
If I know the basics of html and css can I move on to js
Is there something like request.build_absolute_uri but for WebSockerConsumer's
Totally
What should someone do if they aren’t a problem solver
Problem solving is something that you will learn through the time
Take a look at these playlists, you might find something useful https://www.youtube.com/c/veryacademy/playlists
veryacademy is where to come to learn to code for free. Learn website development, tutorials on Python, Django, PHP, HTML, CSS, JavaScript, Bootstrap, WordPress, MySQL and much more.
This channel is all about teaching you simple actionable code, providing you access to code examples that you can use, for free to develop your knowledge and learn...
hlo
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 ?
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?
If you use form.submit(), yes
why might you need to?
Instead of using <button> try using <input type="button">
you can have multiple buttons with the same name and different values
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
why not use hidden input types?
I could, works the same doesn't it?
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
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>
You need closing tags on html and body </body> </html>
I think you need to use <li> instead of <il>
ooooo thanls
///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
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
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
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.
yep...
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...
ty
I started with that video...and then built projects. Started april 15, 2021. My profile has sharable projects I've deployed
i prefer books or docs over vids 😅
I like books too. But when it comes to software engineering having someone cover a process step by step empowers how I learn
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
Also recommend: https://www.feldroy.com/books/two-scoops-of-django-3-x
Feldroy is a small indie publisher of technical and fiction books.
after the video series where did u continue learning django
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.
ah alr
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 😉
i see
You have much experience with python?
uh not much tbh
Or with software engineering generally?
3 months is enough. So long as you've got core concepts down: Lists; dictionaries; logic; debugging; etc...
yeh a basic idea
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.
yep
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.
yeah along with django/flask ill be learning oop
Getting the concept of OOP will help you when read about the underlying framework and theory.
like on weekends
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
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.
django_project is my project name
finally i launched my web server yay
Same , at least once it’s solved it’s solved .
Until you forget and have to crawl through your own code looking for solutions
Hello Guys. Anyone here?
hi
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?
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
Try using a relative path. Maybe the video file is not served, you can check the Sources in the dev tools
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
Indeed. Thank goodness for search and remembering enough, like a key word, or where it was done, to be able to go back for inspiration 😄
In my experience, software development has an abundance of problems. You're not alone. Only today I solved one problem to discover two more. And since then a third has reared its head.
btw i checked your website
great job dude it looks lit
Which one? LanesFlow or Whurthy?
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)
its an inspiration for me (im still not able to create a homepage app 😅 😭 )
Well, I'm 51 years old and hadn't written a line of Python as of April 15, 2021.
@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
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.
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
so far, did any company or professional individual register?
With Whurthy? We've got a couple of clients lined up for Alpha testing. That will help us fine tune. I'm adding event types for one of the clients - and because it expands the market potential significantly. One of those face palm moments missing the requirement to be honest
oh great stuff
Which is why I love Django. Being able to retrofit this sort of requirement is exactly why I love the framework
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
That's a good framework to be learning at school!
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 🙂
not to mention the django rest framework too!
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
Yeah. I keep hearing about it. Just make sure to protect for sql injection attacks
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.
rest api? (maybe its a different thing)
Pretty much. Django has a very solid API framework.
However, if you use it access your own DB(s) it comes with...some risks.
is it not secure
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
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.
i see
I should find the article I read...they presented a case as more serious than that
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
nowadays you almost never need to use raw sql since there are orm's for every database and for many languages
And thank goodness for that!
I kind of get SQL...but I've had no interest in becoming a SQL expert. ORM lets me off of that chore 😉
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
Running PGAdmin for PostgreSQL on my PC was quite a move for me 😄
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')),
]
I don't know what prismajs is, but I'm building a number of different apps. I've just launched a pilot digital library for an org that will be linked to a DB for other service web apps
that's cool!
So I guess I'm saying that Django native can be architectured in a modular fashion
@quiet cipher Looks like progress, bruh 🙂
besides if there's something that you need that django doesn't have out of the box, there's probably a library for that
THere you go 🙂
then i did 'python manage.py runserver'
True story!
a tiny bit of progress
Did you import the view into urls?
into urls.py file?
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
Not quite...sec
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?
also, why doesn't the FK on the OneToOneField prevent this model from persisting?
one sec lemme check
from django.urls import path
from .views import homePageView
urlpatterns=[
path('',homePageView, name='home')
]
yeah i did this^
And you need to ensure you're importing the view
from views import view_name```
That appears solid for urls.py
views.py looks right...no model needed...hmmm
This is why I like tutorials...at least the good ones 🙂
maybe ill go through corey's tutorial once again
Remember that the tutorial is 11 parts or so.
Not just the first vid
yeah but the place where i am stuck is covered in first and second vid
Then you're in good hands. If you follow step by step you'll get there, and the sticky bits will be the teaching moments 😄
Ok. Good luck all. Off to bed.
good night :))
bump
Solid bump, bruh. I'm looking at the model and seeing if anything jumps out at me
To understand why SaveSlotData isn't being saved would need to see the application layer.
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
You were asking why a save wasn't happening. Ahh...you hadn't included that snippet
I responded that in order for there to be a save, something had to trigger the data event
that line save_slot.create() is not saving the data
Right. Because there is more required than that.
.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)```
Helpful tip Questioning relevance when someone is trying to help you isn't going to encourage more help. Just sayin'
well I had already sent the code snippet above
which is the only part involved with record insertion
There you go. I was asking about the logic. I hadn't seen it. Questioning relevance seemed...strange
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...
by default django's Model::save function will either create or update the record
I'm used to using views.py with function or Class Based Views
so forcing a creation or update makes sure that you don't duplicate records
this is in a view
def save is a view
🙂 interesting...I've never had a problem duplicating records. My point, I do the CRUD work in views.py
not models.py
save_slot.create() is the C in CRUD
I have 3 separate files:
app/models.pywhich contains myclass Player(Model):and othersapp/views.pywhich hasdef save():app/urls.pywhich defines the route to the save view
But this snippet calls Models and has CRUD functions.
"save" is the name of the view
hey
that might be causing some confusion
anyone knows Flask
Right. But it's invoking the Models class
That's not answering my question. I don't get what you mean by shortcut
I call model.create, that function calls model.save
thus, create is a shortcut to save
The snippet you posted has a Models Class, and includes functional views.
no it doesn't?
there are no views in this snippet
class SemanticSaveModel(Model): is a class invoking Models
Never mind...I was off to bed 20 mins ago. Good luck
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?
is this for django?
yes django
can you show that file
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.”
hm what else shud be there (im following the official docs)
the app level urls.py right?
write it just like you see in that example here
yeah i literally copy pasted it 😅
lmao
weird
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
@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 ^^
I wanna execute code in backend ~2 seconds after return statement for Flask template is executed. How can I do that?
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>
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.
Settings File
STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'static'
Your static folder is named stactic
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
My bad, thanku so much.
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
Still waiting
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?
On the register button press put return redirect to your login page after your functions run , maybe
But it will be redundant …
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
anyone have any familiarity with smtp (with gmail) for python?
I've used it. What's your question? I know there have been tons of headaches with it due to Google disallowing unsecure apps, then allowing it again
I actually figured it out sorry, but I do have another question if youre available
Sure
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
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.
I was thinking something like that, I would have preffered to return nothing but that wasnt an option that would compile
So I guess the question is, is there no way to submit a form using post that wont redirect your page?
If you just use return,won't it leave you on this contact page?
let me try
This might help
You likely have a history.push(/success) in your api function
Or something or other . Are you using fetch or axio?
In react *
What should i know in Python to learn Django
i wasnt using either, i figured it out though thank you, i just had to return ('',204)
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.
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.
I don't think scaling would matter here 
Maybe not if your project isn't going to need to scale. But uploading media files is a security vector and risk.
It is, also you still can scale vertically to some extent
Sure. But it will become a greater risk with greater growth. #FirstWorldProblems
Personally, I'm working out ways to integrate media uploads to an S3 server, and let it manage the media footprint.
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
I don't do small/personal projects 😄
IIRC, media can be configured through nginx
You can create a media volume along similar lines to serving up static files.
Maybe an issue with using alias instead of root? Don't remember which does what but it might be this
I used root...
Well they use alias 🤔
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
@ionic raft I never had to deal with media files before btw, mainly do some db operations/data processing 
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)
You use django or some other framework?
Django inside Docker
Don't really like using django for rest apis
But I used ngnix to serve static and media.
I've managed to avoid using REST APIs for speaking with the DB. I go fully through ORM for my projects.
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
Yah. I have used API libraries for things like sending text messages
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.
It's harder to work on frontend this way
Since most people use some kind of framework on frontend
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)
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
I'm not sure I completely agree with that premise. But then, I suppose I've chosen to dive really deep into Django to see how far I can take it.
And app design within the Django project allows me to modularize apps
i was the same. started with flask then django , now react and django api
im still not sure i can pull off some of the stuff i did in django , its a rabbit hole
My concern is I see way too many websites functioning very, very slowly with a JS frontend
template rendering really fell out of favor when declarative frameworks like react, vue or angular popped out
Depends on how you code them 🙂
My point exactly
using jinja is a win, jsx is powerful but doesnt seem as efficient
What I know is, the projects I build are crazy fast.
jinja is really powerful, you can use it with stuff other than html too
like yaml
I've done some funky stuff with Jinja
You don't know for sure until you deploy and stress test it 😉
My angular projects are fast too, on my machine
can you use it in react lol, because i got some crazy for loop logic i need to migrate to the new site
"It works on my machine"
Indeed. Which is what we've been doing. Stupid fast. And, when there's a need for app integration then REST API all the way
What are you using btw?
For stress/load testing
What you want to do is to have is create hundreds of thousands of records on a prod web server and DB server (I use PostgreSQL), and see how pages render. I continue to be blown away by how fast Django is
Ehm, how? 😅
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.
Aslo rest api's are easier to test imo
I'd say the same thing for Django...but then I'm diving deep 🙂
I will get to React. Just not right now. More Django mastery first
django has drf (django rest framework) but i find it outdated compared to fastapi and similar frameworks
im asking, because im legit scared of what lies ahead doing my django project in react
When using some kind of frontend framework you usually just create api (might be REST, GraphQL, etc) and use it in your frontend app, backend implementation/language/etc shouldn't matter
And there's no place for jinja2 sadly
yeah but i (maybe stupidly) was doing a lot of the for loop logic to disect data.
Well actually it wasnt too stupid, id have a few filtered tables that were related but needed to display the data together
I've come to really like PostgreSQL as the DB for the backend
Do most operations on db side, it would be faster 😉
Yeah, postgres is one of the most advanced sql db's right now
Rock frickin' solid too!
It's all I these days.
I mostly used it with sqlalchemy since it's more flexible than django orm
I've heard good things.
I use postgres with Django's ORM and have a lot of fun doing the Django-tango 😉
Got an project with 30+ tables. Very complex data model, but it's wicked fast and clients are super happy with the end result.
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
That's why I decided to dive deep.
Try sqlalchemy 😅
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
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"))
i think im going to have to now, the speed was ok its just about how it was displayed to the user
from this
as an example
Just saying that if you iterate over large chunks of data instead of doing that in db then you're most likely doing something wrong
It depends ofc though
ohhh no, the data was filtered beforehand!
In most cases all you want to do on python side is to transform your data a bit
And perform some business logic
I used sqlalchemy and then raw sql before coming to the conclusion the django orm is so much more straight forward
😦
What's wrong with sqlalchemy though?
I stuck with ORM. A year+ later, and working out Postgres and like I said...very happy
saying that, sometimes i found myself sat for hours trying to solve issues which raw sql might have been easier
Another thing to factor is data model design.
sqlalchemy is an orm too
Also sqlalchemy is really close to raw sql, but it depends
Well, when Django's ORM hits a wall I'll be sure to branch out. Until then, I'm diving deep
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."
I also have zero experience with SQL (well mostly zero). So ORM really pulled me in.
You should get some experience with sql then, orms abstract a lot of things
I just get the Django ORM. I have a need, design the data model, code the application layer.
Depends on orm though
On that note...back to coding 🙂
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)
i cant see it
which part
my eyesight isnt that good
i dont want to spam channel, can i DM the snippets zoomed in?
can you type three backticks then jsx then your code then three back ticks
code here
` these
not \
under the esc button
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
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
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
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
Hi there, anyone have advance python web development video tutorial share with me
Hi, i need your help. when i try to install gatsby it gives me this error
I am getting an error in a flask website I am working on. The details are in #help-apple, please help me.
do you know any good proxy list or api ?
api for webdev?
api to make a proxy list using that
or get a new working proxy every miniute
can you do that with fastapi?
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.
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.
Not I. Also, with this being a Python server, the web dev frameworks covered here don't include PHP. However, this is a DB question, so maybe someone in #databases has an idea?
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).
This module has not yet opened in my courses, I'm just starting to learn html x css
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...
You have two options. Self-learn/teach or wait for the course.
If you self-learn Bootstrap will give you a very powerful shortcut for css.
HOWEVER, you'd probably be better of researching the raw css to build borders.
I signed up for a special course
If you're new to css, Flex is quite advanced. I'd focus on borders first.
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.
And bear in mind, that trying to replicate style from another page really requires inspecting the html and css files.
To be honest, I don’t understand what this is about, because, as I said earlier, I’m just starting to figure it out
I'm going to assume that the course has given you assignments based on the knowledge you've learned so far. Look to what you've been shown and try to identify what you can do
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
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?
I have not reached this video yet, I am a person who first does something, and then looks at how it is done
Then you'll be well served to sharpen your research skills. Stack Overflow is a great resource. I'd google along the lines of:
[Stack overflow build border with css]
As someone who taught myself html, css, some js, Python, Flask, Django, htmx, I can tell you that effective research for software development concepts is a powerful skill.
This is what I'm learning in courses.
🙂 Well, if you want to be on the leading edge, you'll have to do the research to self-teach in the course. Or, wait til the concepts are covered.
Looking at those images this is a matter of consistent padding around the text. css has the answers. The advice on "Flex" was solid, and Flex is complex. And, css is also a...less than clear language.
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 😄
That's for sure
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 😄
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.
I'd look out for tutorials on Beautiful Soup for scraping.
Do you want to build forms and retrieve data? You could build that sort of web app in Flask or Django. For either framework, search for Corey Schafer on You Tube. And yes, with json API requests and urllib definitely workable. Depends on their endpoint
I don't want to make web apps. Rather I want to make a script which can access websites, log into it and use it.
Hmmm...then you could do that with pure Python. Ask in #python-discussion
I did. No one replied :p
Have patience. Keep asking
Alright
It's also late in North America. Come back tomorrow.
Ah, good idea.
https://mastery.games/flexboxzombies/
All u need is killing zombies, and u will be flexing through muscle memory in no time at all
That is called web scraping.
Limited web scraping available with just requests library and beautiful soup 4
Fully powered web scraping, working with over javascripted web sites should be done in selenium
(At the cost of higher CPU/RAM and etc consumption)
The book is nice overview of all the stuff. Sharpens the 🔪.
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)
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.
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 ...
What would you say about this one?
https://zoro.tutoreva.com/
If you have doubts about the website, maybe run it in virtual browser first.
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.
Some say it is bad, I say it is great
Because with SQLalchemy we use alembic stuff and having our migrations as a code version controlled in git
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
You have to commit your migrations in django applications too 🤔
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
I don't really remember but shouldn't it return whole model back?
It's probably id and not pk
it seems to work actually if I pass in fields
all only returns the editable fields i guess
Hm, no, it should return all fields 🤔
Yup. Django ORM is super similar
It should return the id of the new object in the response, are you using post() or create() in the view?
ye i just fucked up with fields, works fine now 🙂
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
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
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.
Cs50 has a web development series
But its not very detailed
But its worth a shot
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
what level you at atm? as theres so much online
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
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
.
pure django is pretty good. Theres a bnging tutorial by codemy on youtube to get you started
Join Django & Django REST Framework Course in Udemy
https://www.udemy.com/course/django-django-rest-framework-build-rest-api-in-python/?couponCode=BEDB3246A1704F176E65
Support me on Patreon
https://www.patreon.com/parwizforogh
This is a Django & ReactJS Full Stack Course[ Python Backend React Frontend ] complete course, this will be more tha...
h
or this one is a pretty decent Rest API / React Video. Its pretty long tho
react, boo! vue, yay!
okay thanks! I will look into those
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
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
all the logs is just so i can debug
thanks for the help, i copied the code but im getting some syntax errors, just trying to resolve
its saying both my async functions are declared but never read
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
where's a good place to learn about the microservice architecture?
https://fullstackpython.com/microservices.html may have the answer for ya
Is Django framework named after a Belgarian-born jazz player? I got curious as to why its called Django.
Belgian, but yes it is.
Why people don't like horizontal scrolls? they are actually really cool
Our mouse doesn't generally and typically have horizontal scrolls.
Unless the site treats vertical scrolls as horizontal events, sure
the only thing i would say about it is that it needs to be properly implemented. horizontal scroll where you have to manually click and drag can be annoying
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
is it in a templates folder
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.
You forgot to import the render_template function:
from flask import Flask, render_template
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
and the html should be kept in a template folder..... i searched it on google for 1 hour wondering what's wrong with the code
@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__'
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
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
what language mode do you guys use when writing flask/django templates?
it seems i can only have emmet shortcuts OR have jinja shortcuts.
is it possible to get data on popup without ajax but using javascript in django
Use Base64ImageField from this package if you want to submit an image
https://github.com/Hipo/drf-extra-fields
Extra Fields for Django Rest Framework. Contribute to Hipo/drf-extra-fields development by creating an account on GitHub.
gonna try it
ty
jinja all the way. I've not needed to use a templating language other than jinja.
The joys of learning a new web dev framework. You won't forget that lesson learned 😄
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.
Lazy answer: You can configure a media volume in nginx.
Better answer: Don't use a Django to serve media files for a production project. There are security issues with doing so, and it will mean Django is no longer stateless. If your project grows this will present big load balancing issues down the road.
what's jinja bro ? can you explain it for me
It's actually quite intuitive. Jinja allows you to manage presentation logic so that a web page can be dynamically built. You can do for loops, conditional ifs, call variables, and build urls on the fly. The link above will get you started.
I've pulled off some pretty funky presentation tricks with jinja. Solid AF
Haven't actually used it but looks similar to Flask https://realpython.com/fastapi-python-web-apis/
They should have made her hair "ginger" tho...just sayin 😉
I've always kind of wondered if it's named for https://en.wikipedia.org/wiki/Jinja,_Uganda
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?
I'm sorry, I meant to ask what extension is used in vscode. When I toggle the file to, "Django html" I lose all of my emmet commands
I'm on django 4.0. Can you share your urls.py?
Whatduyaknow! A place called, Jinja.
Still makes me think of ginger hair tho
I've tried the example in official django documentation for version 4.1 no problem
I've got a couple of projects on the go for Django==4.0.4. All good here
They're split into apps the only one ever seeming to be searched seems to be main
Worked fine <4.0 seems
Have you included the new apps in the project's urls.py? All my existing and new url structures are working just fine. I'd also check that the url patterns are built correctly.
Then I'd check that the views are calling the correct templates and are imported into the patterns
wow
from django.urls import include
urlpatterns = [
# App includes
path('', include('app_name.urls')),
]```
are you serious ? i am doing this from django 3.6
Very serious
i suppose it was introduced in version even 2.x
Basically, each app's urls need to be included in the project's urls.py file to be included in the search...
I'm happy for you though, if you're not going to contribute to the discussion no need to chime in thank you though.
yeah
I see thanks a ton. Can you provide any docs?
open the djangodocs
everything is there
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
Right on making sense now, thanks a lot man 🙂
That structure was as true for 3.6 as it is for 4.0 🙂 Good luck
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.
@ionic raft jinja looks same as django tags
Yes. Django templating is based off of jinja 🙂
But whats the point then ?
The point?
Many! Jinja let's you build dynamic webpages with presentation logic. Jinja is a core component of django web apps. Wouldn't work without a way of handling presentation logic
Can we ask for help or guide here?
Ok one more thing can i get data in popup box in django template without ajax but using javascript
I'd check https://docs.djangoproject.com/en/4.0/ for deeper questions 🙂
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
Certainly. Ask away. We won't solve problems, but we'll do our best to point you in the right direction. That way you learn. 🙂
Always remember google is your best friend
I'll include the words "stack overflow" in my searches for code issues
Hey @ionic raft answer this
I shy away from pop ups... I use the messages library instead. I dislike them in general. So can't help I'm sad to say...
pop ups have been abused by scammers and have come to make my teeth ache
Any guide on how do I pass an integer value into foreign key value, I keep getting value error of instance, thanks!
Can you share the error here?
I LOVE htmx!
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!
You need to store the object, not the id. Are you following?
Can you give any docs or something so i can learn ?
Basically, it looks like you're sending the id attribute. Go one level higher and pass the object.
I need to like reference the the integer to the id
A FK is actually the object (or queryset)
If you're filling an FK you need to pass the object (queryset).
Thanks for the guide!😁
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 😄
Bro give me any best link or docs something to learn htmx please
Good to you bro
hmm....I am not a pro at htmx...but I found a solid youtube tutorial...I searched for htmx and django. A couple of banger vids came up.
Ok
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
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 😄
I started with Django 3.x and have never used regex for patterns. Just thinking of it makes my teeth ache. I'd check the django docs and then stack overflow for that question (unless someone else pipes up here of course).
I feel you, how do you pull specific pk's and such?
In the view/query?
I guess
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
how do I scroll down a table in selenium?
@blazing sage ```py
element = driver.find_element_by_id('some_id')
element.location_once_scrolled_into_view
Can also inject js
thanks
but I also have another problem
When I use headless for selenium it won't return any info. What do I do?
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
As this is a Python discord, most experience here will be with Flask and Django. I have no experience with PHP but maybe someone else does.
On the plus side, if you've got a connection between PHP and MySQL, maybe you could google "Stack Overflow PHP MySQL read and display data"
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
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
Alright yeah I agree with that! I tried doing something like that initially but was going for something more like a single image instead of the text & image. Thank you so much!
Thank you!
No problem. Good luck.
While still far from perfect this looks 1 billion times better tysm!
Just going to mess with the size of the images probably
and possibly the font
Yeah it's a good start.
Not possibly. Definitely change it.
It's very out of place
Me too.
I tend to just make something decent, but uninspired/generic. Typically relying on default styling of the frontend framework
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
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.
I hope I do too lol, I think I have learned atleast something.
Yeah, I'm used to ditching a project after a few days because of school messing with my schedule, but with summer I never got that excuse so now this challenge went from a one week challenge to a everlasting challenge 
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.
That sounds both really informative and really painful, though I bet once you get the hang of it it feels very rewarding.
Hi, how can i force a element's scrollbar to always be at the bottom everytime the page is loaded?
i think making all the boxes match the width of the about me box would also make it look more clean
but don’t change the ones that are already smaller than the about me box
css is very fun for me too lol, seems like not many ppl like it though
some javascript to automatically move the page down?
i’m not quite sure what you mean though
ok so i have a div in the middle of my page with an overflow: scroll; and what i want to do in JS is everytime that div is loaded, automatically force the scrollbar to be at the bottom
how long is the div? is it a constant value or a percentage
vh
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
or
grab the length of the div instead of converting
and move the scroll bar down that way
by length do u mean scrollHeight?
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
na
hm i see
can u explain abit more
i thought u were asking if my current method works
instead of refreshing the page, you can refresh specific parts of a page
na that wouldnt suffice because when the user clicks on the link to go to that page, i want the scrollbar to be at the bottom
because if its not at the bottom the user will first see the older messages rather than the most recent
Hello
How do i allow javascript with Flask Talisman ( https://pypi.org/project/flask-talisman ), please?
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
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
I'm assuming you're referencing the one's with the Twitter and Snapchat label, if so I do plan on that, just I'm procrastinating adding OAuth for them :D
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
oh alright i see
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.
Despite the jokes I said in the messages prior to that, I honestly don't completely hate it. The times I do hate it however is when some styling you add requires you to add like 5 things prior to being able to use it.
Is accounts in your installed apps?
Also any errors? Or is it just a 404?
Yes it is
Just a 404, says it can't find it in any urls
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
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
Could you send the accounts.urls?
Somehow it works, I was wondering the same.
Switching from url without use of regex to path has really killed me dude.
Oh wait, I understand how that works now, one is an include one is just a single page.
if it was the other way around it wouldn't work though lol
I think
Yeah, could you send the accounts.urls?
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
?
Is it working? If not, I apologize as I don't think im going to be of much help
Oh
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
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.
I'm currently learning both Java and the c family; I already got way too much on my plate, I will look into it though!
c family as in c/c++, and lightly on c#.
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!
import numpy as np
def keygen(chaos_func, length, *args):
xn = chaos_map(chaos_func, length, args)
key = np.around(xn1e9) % 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
If you use backticks your code will be much easier to read:
if backticks:
print("`")```
Is there a reason you're still using regex in paths?
anyone can help with parsing args in py flask?
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