#web-development
2 messages ยท Page 85 of 1
kk
ok opened
dose it look right?
yes
it's a problem with ur server then
but when i click on the site th other
?
yep, you hav'nt put URL's in there
hm....
they'll be different in a localhost
this
was that the URL?
you put this in chat ```<!DOCTYPE html>
<html>
<body>
<header>
<div class="container">
<h1 class="logo">danoxzilla's web app</h1>
<strong><nav>
<u1 class="menu">
<li><a href="{{url_for('home') }}">Home</a></li>
<li><a href="{{url_for('about') }}">About</a></li>
</ul>
</nav></strong>
</div>
</header>
<div class="container">
{%block content%}
{%end block%}
</div>
</body>
</html>
yes
copy-paste
ok
endBlock
wdym?
wut is for java
#confused
ok
guys it is https://localhost:5000/ and https://about/ tell if it works
?
oh, none of them work, i use netfily to host my sites, it's free
ok
ahhhhhhhhhhhhhhhhhhhhhh
localhost will only work on your machine
Show code that is rendering the template
ok
<!DOCTYPE html>
<html>
<body>
<header>
<div class="container">
<h1 class="logo">danoxzilla's web app</h1>
<strong><nav>
<u1 class="menu">
<li><a href="{{url_for('home') }}">Home</a></li>
<li><a href="{{url_for('about') }}">About</a></li>
</ul>
</nav></strong>
</div>
</header>
<div class="container">
{%block content%}
{%endblock%}
</div>
</body>
</html>
There is definitely some more code involved
The main script
ok
from flask import Flask, render_template
app=Flask(__name__)
@app.route('/')
def home():
return render_template("home.html")
@app.route('/about/')
def about():
return render_template("about.html")
if __name__=="__main__":
app.run(debug=True)
here ya go
.
u got anythin
Try adding some random value to layout as a kwarg and see
render_template('home.html', layout= 'test')
if you don't know how to do that, then I suggest you go do a tutorial...
Some guides to make a chat in flask?
first link on google
another one;
never built one myself but should be pretty easy with websockets
So... maybe slightly offtopic, but how legal is making a content aggregator site with webscraping?
Let's say I want to make a site with news from few other pages
can I just make my main page with titles and links which will be redirecting them to specfic page?
should be fine, there is plenty of other websites like that, can also check t&c on each website you to use to see if they don't allow this
thanks a lot, I will definitely check more information about this when I will finish this project, right now it's just fun ๐
what does flask.request.referrer? Edit: nvm
in django, I need to pass hidden field values from a template to the form, how do?
I am trying to switch to httpx with starlette, can somebody help me with this?```py
message_json = await google_client.get(url, token=access_token)
print(message_json)
It prints out `<Response [200 OK]>`, how do I access the content inside of it?
nvm it's .text attribute ๐
actually, is there a way to have "variadic" forms. I need one radio per db entry
i added a like/unlike funtion to a post in my flask app how can i made to live update like counter, without reload the page?
webscokets, socketio, or eventstream
what are those websockets?
websockets are a protocol that allows 2 sided between a browser and a server
ok, i will take a look, thanks for help
New to coding and just trying to do random things wondering of there is anything wrong with this
Word1 = input("word 1")
Word2 = input("word 2")
Print(Word1 + Word2)
I need some help with django.
Basically, I want to create a form with one field.
The field of that form is going to be some valid ID of a page, for example: /customer/7/, if the user enters 7, it will post a message in that page (/customer/7/), the issue is, I'm not quite sure how to do it, would anyone mind to give a hand?
Why would the user enter an ID manually? Normally, you get the ID from the URL. If you want to display a form already at that URL (/customer/7/), you can get the ID from the route, and pass it in the form using <input type="hidden" name="customerId" value="7"> (or in your template, <input type="hidden" name="customerId" value="{{ customer_id }}"> or similar).
New to coding and just trying to do random things wondering of there is anything wrong with this
Word1 = input("word 1") Word2 = input("word 2") Print(Word1 + Word2)
@rapid nova if you would like to be perfect then python variables are recommended to start with a lowercase letter, but you can also be a rebel if you want and use uppercase
Yeah i always use lower case was just on phone so it auto captitalised the letters
coding in phone is epic
Does anyone know if VSC has run configurations like PyCharm does?
Someone make me understand about import, from something import, when to use '.'
Someone make me understand about import, from something import, when to use '.'
@prisma jackal not sure which channel this should be in... but certainly not #web-development ?
That said, I will send a quick overview in a DM.
@lethal orbit OK, I will be happy
What resources/videos would you recommend for front-end web development? I am learning Django and I think I've learnt a good deal but now I want to learnt front-end as well.
Is html, CSS and Javascript enough?
Is Javascript necessary?
Is Javascript necessary?
@twilit dagger for modern sites / professional front-end/full-stack: yes.
too many sites over use JS
How can I do an if statement to see if an object already exists without getting a Application matching query does not exist? ```python
if Application.objects.get(owner=request.user) is not None:
basically I am trying to make sure the user can only submit once
.get raises an error if it doesn't exist, so you need to try/except it.
ahh that makes sense, thanks patryk!
try:
app = Application.objects.get(owner=request.user)
# app returned exactly one object, so work with it
except DoesNotExist:
# app doesn't exist. You can create it or something
Though I am not a fan of doing things that can raise exceptions in an except clause...
Not sure what you are doing exactly, but probably better to do something like:
does_not_exist = False
try:
app = Application.objects.get(owner=request.user)
# app returned exactly one object, so work with it
return
except DoesNotExist:
# app doesn't exist. You can create it or something
does_not_exist = True
if does_not_exist:
try:
# more stuff
what is the downside of using the 1st method?
You can also nest:
try:
...
except DoesNotExist:
try:
...
except OtherError:
...
Can you recommend some front-end videos
what is the downside of using the 1st method?
Don't do something like:
try:
app = Application.objects.get(owner=request.user)
# app returned exactly one object, so work with it
except DoesNotExist:
# app doesn't exist. You can create it or something
app = Application.objects.create(...)
Because then you can get unhandled exceptions.
Yes
Do you guys know where I could find a good discord channel for help related to moving my web app to PRODUCTION. I am trying to move it to production but I have a lot of moving parts: tensorflow backend ML service, flask backend which connects to a postgresql and a react front end all in separate docker containers... and I am a bit overwhelmed as to how to bring this to production as I have never really done that. Any ideas?
Unhandled exceptions are bad.
Learn the basics of HTML5 and web development in this awesome course for beginners.
โญ๏ธ Contents โญ๏ธ
โจ๏ธ (0:00:00) Introduction
โจ๏ธ (0:01:54) Choosing a Text Editor
โจ๏ธ (0:08:13) Creating an HTML file
โจ๏ธ (0:20:31) Basic Tags
โจ๏ธ (0:36:47) Comments
โจ๏ธ (0:42:13) Style & Color
โจ๏ธ (0:...
html
Learn CSS in this complete tutorial course. Cascading Style Sheets (CSS) tell the browser how to display the text and other content that you write in HTML.
This course will teach you everything you need to know to get started with CSS3, including flexbox and CSS grid.
โญ๏ธCour...
css
This complete 134-part JavaScript tutorial for beginners will teach you everything you need to know to get started with the JavaScript programming language.
โญ๏ธCurriculumโญ๏ธ
This is a stand-alone video but it follows the JavaScript curriculum at freecodecamp.org. Access the cur...
js
Thanks
for front-end
You used these?
thanks guys
jesus how df do you even survive watching all of those
videos are boring af and will go in one ear and out the other
far better just messing around with stuff and getting the hang of it
yeah why use 3 hours to learn something from a master when you can spend 10 hours wasting time "messing about" right @quick cargo
I mean if you can legitimately watch a 3 hour video and take in everything and put it into practice immediately with No need for practicing or looking up anyway then you're probably the first person in the world todo that
you're gonna spend well over 10 hours messing around even after watching the videos lol
This was the 2nd site i ever made going from Zero html and css and JS, You learn a hell of alot more by actually doing something than watching someone do it instead imo
watch learn apply that's what works for me
I find videos nice when something is utterly failing, as videos tend to contain all actions needed to get something, whereas articles tend to omit things at authors will
Im not saying videos are bad
if something else works for you, that's alright too
im just saying 3 hour mega sessions are pretty pointless in general
they really work for me, especially when I follow along
tinkering has never worked out for me, if I'm just starting out
No one says you have to watch all 3 hours in a row... Just learn, practice, and keep watching.
You can easily spread it over a week, and you can watch sections multiple times.
If you're not learning from the video, then look for another source ๐
Does anyone know of a Python library / framework that can do similar things as huginn (which is written in ruby)? Hereโs a link to the huginn repo if you are not familiar with them: https://github.com/huginn/huginn
I really love the system but as I donโt write ruby, it makes it hard for me to extend / debug it. What huginn is: a system that allows you to create โagentsโ and listen to events and then do something with them. Kindda like rolling your own IFTTT but self hosted.
I have looked into commercial services e.g. Zapier but they quickly became expensive when I am having too many events. Then I looked into writing my own but I feel that something like this must exist already and donโt want to repeat the effort, and at least it would be easier if I could simply write the custom parts on top of it.
Any help would be appreciated. Please tag me if you reply (or tell me if this doesnโt belong on this channel). Thanks!
with self.engine.begin() as conn:
ticker_data.to_sql(
'ticker_data', con=conn, if_exists='fail')
Using sqlalchemy. How to catch if rollback occured?
@earnest trail i dont know of a python equivalent, but it seems like a very interesting tool. maybe worth learning ruby for ๐
for large django projects templates folder should be separate for each app?
@fast basin I don't use Django, but I'd certainly recommend you to do so.
If some template is used by more than one app you can leave them in the templates folder root or just put it where it mainly belongs and access it on the other app by constructing the path to it. If your project is growing fast, sooner or later you'll have so many templates in one dir that it'll be hard to maintain and find the one you're trying to access
Is there an easy way to send form data to a specific page (by using the field the user has entered, for example, the user enters 123, the form data will be sent to /users/123)?
(Django)
the templates folders of the app I'm mainly working in looks like this, helps me a lot to keep track of my changes
@native tide which framework are you using?
Django
the templates folders of the app I'm mainly working in looks like this, helps me a lot to keep track of my changes
@sly canyon
you got it nicely maintained I'll follow the same approach.
I'm not sure how to handle that in Django, but most likely you'd just need to set the action atrribute in your form tag, specifying the URL that will receive that POST request
Maybe something like
<form action="/users" method="post" novalidate>
You'd still have to work on your /users POST handler to capture the form data and redirect the user somewhere, displaying something.
in django i think you need to associate the URL with a View that renders the Form in urls.py
i'm not 100% how it works though
there is a lot of indirection w/ views in django @sly canyon
the <form> itself is generated by an instance of a sublcass of django's Form base class
you just slot a placeholder for said generated form into an html template
Might be similar to Flask-WTF's FlaskForm
But you'd still have to render that using Jinja2 right? The template might be the key to accomplish what he wants
ah so you can add a custom action= if you want to
Yup, very similar to Flask
templates/_formhelpers.html
{% macro render_field(field) %}
<div class="{{ field.name }}-wrapper">
{% if field.type == "BooleanField" %}
{{ field(**kwargs)|safe }}
{{ field.label }}
{% else %}
{{ field.label }}
{{ field(**kwargs)|safe }}
{% endif %}
</div>
{% if field.errors %}
<ul class=errors>
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
{% endmacro %}
templates/some_blueprint/my_form.html
{% from "_formhelpers.html" import render_field %}
<form method="POST" action="" novalidate>
{{ form.hidden_tag() }}
<!-- Name -->
{{ render_field(form.name) }}
<!-- Email -->
{{ render_field(form.email) }}
<!-- Phone -->
{{ render_field(form.phone) }}
{{ form.submit }}
</form>
(Kind-of custom made, 'cause there are easier ways to render fields)
at which point then yes, you need /users/<int:user_id> in your URL spec, which handles the form data with some kind of View
yeah the flask community sure has done a great job of emulating all the batteries that django includes ๐
(nb: i prefer the modularity of flask)
I feel like flask is more customizable (not that I have ever tried Django), it also seems like it only includes things as we need them to be included (that's the lightweight aspect of it)
@sly canyon In an image compression django web app. The user will upload an image that will be stored in my DB first? or I have to use the image compression algorithm before inserting inserting the image to DB then return that image to user as a compressed image?
I feel like flask is more customizable (not that I have ever tried Django), it also seems like it only includes things as we need them to be included (that's the lightweight aspect of it)
I have found django fairly resistant to customization. While the options are there, django becomes much more difficult when you start going against the assumptions django makes about how it should be used. I have not used flask, haha, but I assume this to be true
In an image compression django web app. The user will upload an image that will be stored in my DB first? or I have to use the image compression algorithm before inserting inserting the image to DB then return that image to user as a compressed image?
I would save the image url to a DB, then save the image to a local file, then perform compression, then send the image back if it needs to be.
@acoustic oyster You mean saving the image like the static files? for short perioed of time
yes
@fast basin again, I have no knowledge of how Django works whatsoever. But if I was in your shoes, I'd store the images in an temporary user_uploads folder, compress it, validate it, then I'd store it in the DB.
in django I save images to "media"
as per standard
very similar to how static works
I used a postgres database and saved it directly to the database
you could then delete it if you needed to
I used a postgres database and saved it directly to the database
while this certainly works fine, it is not optimal for performance
--to have a DB serving images directly
No, sending a file would be better
But managing the files can be difficult
And I have never attempted to save binary data to a database before so I went this route
well thanks as more of you guys suggesting to store it in server disk rather then DB. I will go with this approach
I would recommend using an integer identifier used as primary key in your database
Or any other value you use as primary key
What does <span> do?
it creates an inline text element
https://docs.python.org/3/library/imghdr.html might help you to validate img data
As fileName could overlap and instead of modifying the file name, saving it using the key as name and then keeping the original name in the table in the database
it is like <p> but the default style is inline, iirc
https://github.com/GoogleChromeLabs/squoosh might help you compressing img data
not sure if Squoosh is supported as a back-end solution
Also, unless someone uploads a uncompressed image, itโs probably already gonna be as compressed as can get unless you change the format
Or any other value you use as primary key
@native tide could be useful. if i store them in db.
it creates an inline text element
@acoustic oyster that is true, but I don't know how it works and when to use it.
Are you going to use a database to maintain image meta data?
Like ownership, upload time, etc
https://github.com/GoogleChromeLabs/squoosh might help you compressing img data
@sly canyon I was thinking of implenting the algorithm on my own but if there's a library why not to use that ๐
and prevent overwriting existing images who share same file format and name
@prisma jackal you would use it wherever you need inline text.
This means it mostly ends up being used for small areas of text, perhaps embedded in a block tag. i.e if you want some different style for some part of a paragraph, you could do something like
<p>words go here, but <span style="color: red;">this</span> is special</p>
Thx
Are you going to use a database to maintain image meta data?
@native tide No anyone can upload as guest.
@fast basin now that I'm thinking it straight I don't think Squoosh will help you to automate that task, but PIL along with numpy might do the trick for you, maybe scikit-image or something. You can also rely on third-party APIs to POST the image and get them resized/compressed.
@fast basin now that I'm thinking it straight I don't think Squoosh will help you to automate that task, but PIL along with numpy might do the trick for you, maybe scikit-image or something. You can also rely on third-party APIs to POST the image and get them resized/compressed.
@sly canyon
Thanks for the reference. I will implement that with Scikit PIL etc.. in the morning.
can someone tell me if i can set media query range
i want to hide icon from 992px to 768px
BUT after 767px i want to unhide icon
you should just make multiple queries then.
like:
min-width 768px{display: none;}
min-width 992{display: block}
something like that, but that actually is code and does what you want, haha
and it would be visible in the base css (without media query)
Django question: how to override abstractuser email field to be required and unique?
Django question: how to override abstractuser email field to be required and unique?
@honest dock create an abstract model that inherits from it and override the field...?
what are you having problems with
I can't seem to find why my blueprints are not working for this flask app I am trying to build. I keep getting requested url not found errors when I run the app. I just started trying to learn blueprints compared to routes being in just app.py so I am rather new to this. Any advice on what I am missing would be super awesome.. nevermind I found the problem. thanks
With Django and getting images to show. How many different reroutes or variables do you make for them to show? Also, whatโs the {{ object.img }} ??? For it to show? I keep getting stuck
nevermind I actually figured it out finally haha.
Does anyone have experience with flask, heroku and postgress?
@honest dock you might need a custom usermanager aswell
just out of curiosity, what os are most people developing on?
Most beginners I have noticed use Windows, others are on Unix system, be it Mac or GNU
variety of things, for django, it shouldn't matter a ton
I'm on Debian, but seems like Python dev isn't so bad on Windows these days.
Anyone know like a software or how you start to make a really custom and unique website like apple? Something that is not low quality and is like for a big business.
Anyone know like a software or how you start to make a really custom and unique website like apple? Something that is not low quality and is like for a big business.
@native tide What you're looking for is a web framework. Though it's possible to do it that using just html, css and Javascript, these frameworks make it much easier once you have learned their basics.
some frameworks are react, angular and vuejs
I understand how to do the stuff my problem is finding the right software or studio to do it in
if you're a complete beginner, you need to learn html, css and js and use something like django for backend (python
)
I understand how to do the stuff my problem is finding the right software or studio to do it in
@native tide you can just use a normal code editor, there's no specific software really. if there is any such requirement, it'd be mentioned on their site
IgnisDa is typing...
yeah i know i am
Hello, I wanted to create a WebApp using Python CGI, using which i can open a graphical applications inside the browser itself by just writing the application name. Can someone help me in that.
Hello, I wanted to create a WebApp using Python CGI, using which i can open a graphical applications inside the browser itself by just writing the application name. Can someone help me in that.
@mystic dagger ask this is #user-interfaces
is anyone familliar with setting CSP using the meta tag? I'm getting a mixed content error when trying to access an api I wrote. The site is https and the api is http. I tried using a self-signed ssl cert, but I couldn't get that working.
may i get some help with an html web
site?
<!DOCTYPE html>
<html>
<body>
<header>
<div class="container">
<h1 class="logo">danoxzilla's web app</h1>
<strong><nav>
<u1 class="menu">
<li><a href="{{url_for('home') }}">Home</a></li>
<li><a href="{{url_for('about') }}">About</a></li>
</ul>
</nav></strong>
</div>
</header>
<div class="container">
{%block content%}
{%endblock%}
</div>
</body>
</html>
guys hello
what exactly is your question
ahhh
ok my question is
when i am launchijg it
it gives me an
error
which error u want to kno
post it?
it says layout not defined
full traceback pls
hm
I don't remember if you can do url_for in jinja or not
Hey @gleaming basin!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
โข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
โข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
noooooooooooo
try changing to relative urls
how are you rendering this?
which one actually uses "layout" as a var
about.html
home.html
layout.html (main temp)```
which one actually uses "layout" as a var
@warped timber u mean <>
send the python code that render_templates this
ok
from flask import Flask, render_template
app=Flask(__name__)
@app.route('/')
def home():
return render_template("home.html")
@app.route('/about/')
def about():
return render_template("about.html")
if __name__=="__main__":
app.run(debug=True)
wait when do you show layout.html
it is up
ok
does home or about do anything with layout.html
show please
yeah ok
but how is layout.html being displayed
because your code currently only has home and about
this is layout.html
ik
this is what it is for
currently you haven't posted anything that actually uses/displays it
yes
hey guys, can anyone explain me how to hash a user password in Django on an AbstractUser via a CustomUserManager ?
def create_user(self, first_name, last_name, email, password, **extra_fields):
"""
Create user with the given email and password.
"""
if not email:
raise ValueError("The email must be set")
first_name = first_name.capitalize()
last_name = last_name.capitalize()
email = self.normalize_email(email)
user = self.model(
first_name=first_name, last_name=last_name, email=email, **extra_fields
)
user.set_password(password)
user.save()
return user
class CustomUser(AbstractUser):
username = None
first_name = models.CharField(max_length=255, verbose_name="First name")
last_name = models.CharField(max_length=255, verbose_name="Last name")
email = models.EmailField(unique=True)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["first_name", "last_name"]
objects = CustomUserManager()
def __str__(self):
return f"{self.first_name}, {self.email}"```
Can i put DELETE method on a form tag in html?
with self.engine.begin() as conn:
ticker_data.to_sql(
'ticker_data', con=conn, if_exists='fail')
@polar lantern Anyone an idea?
@weary dragon Not with plain html
@strange briar just use this Manager https://github.com/IgnisDa/unixporn/blob/master/backend/accounts/managers.py
@versed python I still have the same problem, but my app is not connected to a front-end via api yet, i'm just trying to create a user via django admin page
so is it normal ?
when i look at django admin page i see the user password field as plain text, when i create a super user the password is hashed
when i query my db via graphql the user password is also plain text
When I want to use bootstrap for styling, do I have to put all the scripts from get started page in every template? Or just main template?
if you use django layout you can keep the CDNs on your layout.html
When I want to use bootstrap for styling, do I have to put all the scripts from get started page in every template? Or just main template?
@maiden kraken depends on template. If you extend abase.htmltemplate, you can just keep them inbase.htmlwhich is good practice.
okay great. I have base.html with this bootstrap stuff. Can I use it then inside my template which extends base?
ex. i want to create 3 columns
yea normally you can
thanks a lot guys
when i look at django admin page i see the user password field as plain text, when i create a super user the password is hashed
@strange briar oh yeah, that's cause you have to change the UserChangeForm cause you changed to custom user. Look at theaccounts/admin.pyin the repo i sent, and use that. It should work.
Hello everyone,
I want to add reset email feature to my app and wanted to ask if I could use something other than flask_mail?
I checked PyPi and saw it had no update since 2014 , is it possible to do that using smtplib?
@royal radish there's a flask-sendgrid module. But ofc, it is for send grid. Flask-user has mail capabilities as well. Also, you could just use python's inbuilt email package i guess. You don't really need something flask specific
http://flask-shell2http.readthedocs.io/
I have created a Flask extension that can convert any command line tool/script into a RESTful API with ~ 5 lines of code. It's very extensible and feature rich. My use case for this was docker to docker communication b/w microservices with binaries/packages.
how do i make vscode not giving me squiggly error lines on django models whenever i use the attribute .objects
are you using pylint?
@bright spindle Get PyLint
if yes then you'll need to install pylint-django as well to get rid of those warnings
Ok so what exactly is the use of JS in web-development?
making page interactive?
Like??
basically (simplifying a bit)
whenever you do something on the page and something changes
that is done with JS
Like drop-down menus and searchbars?
uh
well
I think dropdown menus are standard HTML
for searchbars
autocomplete
for example
can only be done with JS
Hmm ok thanks
This is a question regarding Django -
We are building a DB/model for API routing to React frontend, the person working on the front end asked for information to be keyed as follows, as an example:
"ttop": {"full": 'Text Topical', "description": 'description text'}
but I'm not sure how to accomplish that in models, the "ttop" field is also a model, there will be others e.g atop, tbat, abat, free etc as shorthands for "text battle", "audio topical" etc, and that is what this dictionary is intended to define -
I currently have
battle_short = models.CharField(max_length=5)
battle_full = models.CharField(max_length=50)
description = models.CharField(max_length=500)
@strange briar oh yeah, that's cause you have to change the UserChangeForm cause you changed to custom user. Look at the
accounts/admin.pyin the repo i sent, and use that. It should work.
@versed python Hi again Ignis and sorry to disturb you, I followed your instruction and could implement the hash on my passwords so thank you ๐ however, this code is quite blurred for me, if you have a bit of time, can you explain it to me ? there are several files i had to implement like forms.py, modify admin.py..
yeah sure, dm me with what you need @strange briar
ty ๐
Hello, I got issue deploying a django app on wsgi server. When i run django app with runserver 8080 it works as expected, but when i tried to host django on cherryPy server, i got issue with django that he can not find module name settings. I looked up on stackoverflow but, the solutions over there did not work correctly. I can post some pictures of my project structure.
@hidden trout runserver is not supposed to be used in the actual production server, instead you need to use wsgi.py
@versed python i know that, this server is only used for testing purposes or debuging. I tried to deploy my app on cherryPy server, with wsgi.py. But when i tried to start django on cherryPy i got this error ModuleNotFoundError: No module named 'mysite.settings'.
you need to manually need to insert the package into path
@dapper tusk you mean with sys ?
ye, sys,path
you need to manually need to insert to package into path
@dapper tusk are you sure? I never had to do that
doesn't django do that itself?
no
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'politika.settings')
application = get_wsgi_application()
```is all the default wsgi.py does
depending on how your wsgi server works, it can sometimes not be needed
yep and assuming the project root has an init.py, it should get inserted into path automatically
but sometimes you have to modify sys.path
no
the containing folder does not become a package
unless you do -m folder.file
i got the same, but before setdefault , I tried to append path to settings module. I will send you my project structure if thats okey?
I suggest inserting at 0, and use the path containing the mysite directory
the containing folder does not become a package
@dapper tusk is this a shortcoming of python or the server in question then?
it is just not how python works
I'm so confused about this...
if you have a.py and b.py in mydir, then the import is import b, not import mydir.b if you run python a.py
if you instead do python -m mydir.a, then you would do import mydir.b
personally, I dislike this system
im very new to flask and i want to know how to add CSS to a HTML Template? Im not sure if im doing it correctly
Can't wrap my head around this. Lets say I have this project structure
and I'm calling wsgi app from cherryserver.py, aren't the settings in same directory. I mean they have the same init file so it should find my module if I'm not mistaken
@dapper tusk
Hello after completing basic python i am starting web development with flask
then your settings module would just be settings
Any suggestion for me!?
Yep, it should, but i got this error message that it No module found 'ResourceManager.settings'
Hello guys, using Django how would you add validation constraints to a modelform?
For a first name, will you use widgets = { 'first_name': forms.TextInput(attrs = {'placeholder': 'Alicia','minlength':2,'maxlength':30} for example or is there a better/other way to do it?
@umbral echo it's much easier to use validators
first_name = forms.CharField(validators=[first_name_validator], widget=forms.TextInput())
something like this
look into the django docs, they explain this is detail
Ok thanks a bunch! I tried to make one, one day, such a fail ! I'll try again today, because I always block on this
added this to mine wsgi.py. And still got the same error when i try run it on cherry. @dapper tusk
try .insert(0, BASE_DIR)
tried still the same issue
try putting import ResourceManager after the sys.path.insert
@little furnace did you find it?
no
You gotta have an static folder in your project then put the css file in it.
How can i do that
@dapper tusk its greyed out like shown in a picture
@little furnace Add an static folder in your project folder
should i name it just static?
How do I show specific data on specific pages, I want to show data only if the page ID equals to the form input value (don't ask why please) so each page will see something.
from a form ^ (Django)
Yeah just static
like that?
Do you think that i got issues with path because of the naming of my project. If you look closely I got ResourceManager as project, then in the same directory I have Resource manager... which was created with django admin. @dapper tusk
it makes it somewhat annoying to debug, but I have gotten similar structures to work
Yeah thats right
I'm really out of ideas, what should I do next. Do you have some pointers to what had gone wrong? @dapper tusk
try pkgutil.iter_modules and try figuring out where that goes
@nimble epoch thank you so much! It worked! ๐
@little furnace yw
Hey guys I am using Flask as a back end for my project on the front end I am using Javascript to send the following request
fetch('http://127.0.0.1:5000/updatetask', {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
'TEST': 'test',
})
})
and on the backend I am accepting the request with
@app.route('/updatetask', methods=['POST'])
def update_task():
if request.method == 'POST':
print(request.json)
print(request.form)
return 'Testing'
and for some reason neither json or form gets any data
no point having that check because flask will return METHOD NOT ALLOWED if its not already a POST request
with the request I am sending I would expect request.json to get data
@dapper tusk i tried and i got 3 modules inside
i got ResourceManager,SimpleResourceManager, manage
that seems correct
No it is a dictionary
odd
@umbral echo Yeah sure, if you need help, ask me.
@dapper tusk is there any way around this issue ? if everything seems correct
Reposting because I still need help :/
How do I show specific form data on specific pages, I want to show data only if the page ID equals to the form input value (don't ask why please) so each page will show something else based on the user input.
(Django)
I'm working with Flask. Is there a way to acces to the "user_id" variable inside the html, without pass it in the render_template ?
@user.route("/<user_id>/quizz/")
Reposting because I still need help :/
@native tide You will probably need to override__init__method for your form class to make dynamic forms (that what you need right?)
I'll give you a better example, say there's a form page, there's a field called 'ID' or something, now, I want to display the form data only on that specific page ID (user/ID/ or user/5/), and if I go to another URL (user/9/), it won't show that form data on that page.
oh that's pretty easy, you don't need to mess with forms for that.
look into setting permissions on a per-view basis @native tide
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
-webkit-box-shadow: 0 0 0 30px white inset !important;
}
Input becomes yellow after auto input
however i CANNOT get it to go back to white. Above CSS is the only solution i could find that didn't involve JS
How can I have multiple image uploads with wtforms ? The user can upload max of 4 photos, but I don't want to create 4 form fields
if youre using django that can be done using formsets. Idk what wtforms is though. @past cipher
no im using flask
I figured out I could use MultipleFileFIeld but that means if they drag and drop, it always replaces the last file
Using selenium. Suppose a div has an attribute 'data-timeslottime', and i want to extract the value associate with this key (Sorry, if i am using the wrong terminotlogy), how do i do that:
<div id="book_57ef00ac-8e7b-431c-b18c-b8b987fec892" class="time-slot" data-slotclub="North York Centerpoint Mall" data-slotdate="Tuesday, 8 September 2020" data-slottime="at 7:00 AM">
find_element_by_xpath
I understand, but how do i get the value associated with data-slottime
I want "at 7:00 AM"
use .get_attribute('slottime')
Thank you
pretty sure anyway, not used selenium in a long time
Why isn't "ID" being generated for new entries in a model?
from the MongoDB, it is recording them with ObjectID, it is breaking the Django
_id
:
5f565ebd9351425d2c8a516d
battle_short
:
"ttop"
battle_full
:
"Text Topical"
description
:
"Text Topical Battle, an epic clash of literary might"
then gives the following error:
rather, when I try to access the data from admin panel it says "Battle type with ID โNoneโ doesnโt exist. Perhaps it was deleted?"
from json:
[
{
"id": null,
"battle_short": "ttop",
"battle_full": "Text Topical",
"description": "Text Topical Battle, an epic clash of literary might"
},
id there is read as null
do all i need is Requests to interact with a web api i made to do RESTful stuff?
Iโm trying to enter a command to be run in terminal, for โsource ./venv/bin/activateโ but it comes up with the โexeโ error, but, thatโs exactly what Iโm activating. whatโs does ${echo) do?
are you using windows or Linux @frozen python
Django again. When using auth_views.LoginView from django.contrib.auth do I have to put templates inside /registration folder? Or can i somehow change path?
Django again. When using auth_views.LoginView from django.contrib.auth do I have to put templates inside /registration folder? Or can i somehow change path?
@maiden kraken set thetemplate_nameattribute inside your view. Or you can override theget template_namemethod if you want more fine-grained control.
@versed python
I have it like this, I think this is what you are talking about
path('login/', auth_views.LoginView.as_view(), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
but with like this I have keep my templates in registration folder
path('login/', auth_views.LoginView.as_view(template_name='your_filder/login.html'), name='login'),
@maiden kraken
I suggest you actually Subclass the django login view and then use it though. This will enable you to extend that view in future easily @maiden kraken
I am not really sure if it is within my reach for now
I am using functions in my views, not classes
it's really easy
# accounts/views.py
class MyloginView(auth_views.LoginView):
template_name = 'myfolder/login.html'
# accounts/urls.py
path('login/', MyLoginView.as_view(), name='login'),
@maiden kraken
Flask-WTF question.
I have this script in in the conversion.html:
<head>
<!-- [...] -->
<script async src="https://www.googletagmanager.com/gtag/js?id={{ gtag_id }}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '{{ gtag_id }}'), {
'send_page_view': false
};
gtag('event', 'generate_lead');
</script>
<!-- [...] -->
</head>
But I don't think Google would track the source of that conversion as the "conversion" page serves several different products and their generate_lead event doesn't support any parameters that references the source of the event.
So, I want to trigger that script only after the form validation as such:
@bp.route('/some-route', methods=['GET','POST'])
def some_route():
# [...]
form = ConversionForm()
if form.validate_on_submit():
# Here it should trigget that JS script
# [...]
return redirect(url_for("conversion"))
return render_template('some_route.html', form=form)
@bp.route('/thank-you')
def conversion():
# [...]
return render_template('conversion.html')
Is that even possible?
@versed python thanks a lot man, I will save your message and try this solution tomorrow
sure
Hey, I am just curious. Does anyone have a good idea of how to upload images/videos using flask?
@versed python okay that's not so scary, its similar to creating custom model. You are just creating custom login page inheriting everything and changing only one value. Thanks a lot man
@versed python Mac
@versed python okay that's not so scary, its similar to creating custom model. You are just creating custom login page inheriting everything and changing only one value. Thanks a lot man
@maiden kraken yep very easy
@versed python Mac
@frozen python i dont have experience with mac but maybe you should search of how to activate virtual environment in macos on Google
I am pretty sure you can install an env package with python, and it will handle it
at the beggining of this tutorial he talks about it, and from the way his browser images look I think it is on mac os
actually he is using mac os, I remember him saying that
Is Django good tool to make discussion forum or is it usually made in PHPbb (this is what i remember was used long time ago)?
well PHPbb is a forum out of the box. Django is just a generic web application framework.
you could also look into Discourse
there's also drop-in Forum apps for Django though, https://djangopackages.org/grids/g/forum/
Misago or Spirit
thanks a lot man, it was just an idea that poped into my head how to expand my website. I will check Misago or spirit
My question: does anyone have a good resource on implementing external authorization with Django. I have a no-fun setup of CAS for authn and authz based on LDAP attributes I'm porting from another application.
so i;ve searched online but no topics on that
i wanna make a function that when a submit button is pressed its checks a form's input
and if its contains a word from a tuple (bad_words tuple) its gonna reload the page or pop up a message
One sec, lemme switch to pc
I believe you can do something like this:
class MyForm(forms.ModelForm):
model = User
fields = ["username"]
if request.method == "POST":
if form.is_valid():
for content in form.cleaned_data.values():
content = content.split()
if any(True for x in content if x in bad_words):
return render(request, the view)
else:
form.save()
dont you dare answer this now! this took time!
haha
and if its contains a word from a tuple (bad_words tuple) its gonna reload the page or pop up a message
No!
Bad!
NOOOOO
ok brb lemme try linuxpro suggestion
x in set is much quicker than x in list|tuple as those need a sequential scan.
this is somewhat pseudo code. But I think this does what you want.
I would personally add this check to the "is_valid" method of the form itself to make things easy
how so
I should probably have tested this solution, but I just woke up and dont feel like messing with django xD
hooray
so its a win win
If you have 10,000 words to check in a 10,000 word tuple, it's 100,000,000 operations. 10,000 words in a set of 10,000 words takes around 10,000 operations.
Using the right data structure is a really important part of optimization ๐
hey, not sure where else to ask this, but this channel seems to be the best match since I'll be using the following for web design mostly:
im making an http server from scratch with sockets and i got the basics down and am able to render html files in the browser through the server but i want to take it to the next level and make some sort of browser sync system, when a file changes in the working directory, make the browser refresh automatically. im not looking for a full on tutorial just some pointers so i know in which direction to take this.
Any help is much appreciated!!
also: I did not know about that, this will change how I program forever
Well, if you are using websockets, then you can use JS for the front end and then your browser does not need to refresh
hm ok thats one option
wait, do you mean like a development server where when you change the backend/python it automatically refreshes?
If you just need the front end to be a live stream of data from the DB/API/data on the backend, then I think websockets with JS on the front end is the way to go.
yes, good. Because my code was from memory and I was not sure if it would work haha
lets try now
test it out and let me know what errors you get xD
oh, you know what, I got fancy with the generator, but this would actually be more efficient as a loop where you break/return if a match is found. Since there is no need to check the rest of content if a bad word is already found. This should work fine though
oh, you need to return your redirect at the end of the view (if they are successful)
did that
lie return redirect()
but that also means that the form was valid in that test
when i went to signup
its popped up that
is possible to do the opposite
so like
if form is valid its done
else its detects a bad word its redirect or pop up an error
show your code, it is basically saying your function is not returning anything
your form is not valid, you need a return at the bottom, for the case that the method is not "POST" which it will always be "GET" the first time you load the page
Does anyone have any idea how I use bootstrap class tags with flask? I tried just creating a div and adding the class, but that doesnt seem to work
@acoustic oyster so like replacing the POST with GET
one sec
i wish i was one of ur students so u can teach xd
nvm, I am stupid
class MyForm(forms.ModelForm):
model = User
fields = ["username"]
if request.method == "POST":
if form.is_valid():
for content in form.cleaned_data.values():
content = content.split()
if any(True for x in content if x in bad_words):
return render(request, the view)
else:
form.save()
return render(request, your_signup_form)
like this
haha, happy you worked it out xD
I used .className and not just className
in your code, you ONLY return anything if the method was "POST" which means a user pressed the button to make a "POST" request, but when you type a url in a browser, or click a navbar link or whatever, you will be making a "GET" request.
So in your code: the first load is NOT a "POST" request, so it ignores what is in your if statement and goes on to not return anything
@acoustic oyster btw what does 'request, the view' means like the function?
cuz like the code is in views
and im using uh UserCreationsForm
@acoustic oyster no all im doing is something like the http.server module but with my own preferences
sorry, that is supposed to be the same as return render(request, your_signup_form)
ill be using it for normal html/css/js
Do NOT use the inbuilt http server for production systems
heres the code
i dont really like viewing html files via file:// protocol haha
yeah, that looks good, this should not error immediately now xD
so we can see if my form magic works
hmmmmm the magic code is fine but the form got noobed
you need to pass the form in context with the same name you were using before
you need to pass the form in context with the same name you were using before
context = {'my_form": form}
return render(request, your_signup_form, context)
context = {'my_form": form}
return render(request, your_signup_form, context)
lel, you need to pass the form in both returns
the way you have it, it will load the form the first time, but if you submit it with a bad word, it will render the template without a form
define context right below your form, now context is not defined in the last return
lemme do some hardcore typing, uno momento
spice
can you paste your code in instead of snippet?
alright
def signup(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
context = {"form": form}
bad_words = ("shit")
for content in form.cleaned_data.values():
content = content.split()
if any(True for x in content if x in bad_words):
return render(request, 'registration/signup.html', context)
else:
form.save()
return render(request, 'registration/signup.html', context)
it looks good, lemme just make some tweaks to your code.
from django.contrib import messages
def signup(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
bad_words = ("shit")
for content in form.cleaned_data.values():
content = content.split()
if not any(True for x in content if x in bad_words):
form.save()
messages.success(request, "Account successfully created")
else:
form = UserCreationForm()
context = {"form": form}
return render(request, 'registration/signup.html', context)
I made the conditional a little more confusing, but this works better without doing any more confusing refactoring. I added a success message, so the user will be notified that their account was successfully created. I forget if you need to add something to the template for the message though
Hello, I have a list of friends I would like to add as friends on facebook. But I dont know how I can add them automatically. Can someone shed some light on how to do this? (They are residents of my building which I am making a facebook group for)
@inland gate you would need to see if the facebook api has this ability. I imagine they are protective over this type of thing to prevent bot/spam accoutns
haha, no problem, is now lunch time here xD
So I will also be back. I will probs be lurking, but feel free to @ me
@acoustic oyster Yea I would assume so, thank you
Think it might be easier to just put up a note in the hallway ๐
Think it might be easier to just put up a note in the hallway ๐
@inland gate Print one with a QR code. Easier than typing in an address, if people can just scan it and get a link to your profile or group...
@lethal orbit Y, great idea! Thanks
(Also put a URL / name for people who don't have a QR scanner installed, of course)
Does iPhone include that? If not: that is their punishment.
ยฏ_(ใ)_/ยฏ
@acoustic oyster back
Haha, I'm eating now. I think i see my mistake though. Will be back on in a bit
alright sir
probably if request method isn't POST
^yeah, I messed up my tabbing haha
def signup(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
bad_words = ("shit")
for content in form.cleaned_data.values():
content = content.split()
if not any(True for x in content if x in bad_words):
form.save()
messages.success(request, "Account successfully created")
else:
form = UserCreationForm()
context = {"form": form}
return render(request, 'registration/signup.html', context)
okkk!!
@acoustic oyster ayye thanks...ig its works,when i typed shit in input and clicked the button its refreshed
now i will test it one more time
and make it an api,i will try my best and credits to u :p
I am avoiding doing productive things by being as helpful as can be
^saaaaaaame
and yeah, you could include a message for this as well. You could probably find a way to notify of the issue in the form.
Make sure you check admin panel as well to make sure it is not saving
/is saving when you want it to
I am avoiding doing productive things by being as helpful as can be
its ok if some ppl like studying the code and understanding them by theirselves and not just copy paste then go like that
Also, be sure to use a set and not a tuple xD
thanks @lethal orbit @acoustic oyster
bad_words = set("shit poop fudge brownie".split())
lol ye
Instantiating a set also has a bit of overhead, so you can do that in settings.py once and import it in your script.
no problem
For a small set, it's negligible though
(and for a really small set, a tuple can do the job too)
i will use google banned words which is hella big
haha
yes
and load it in settings at startup.... then you save the with open("badwords.txt") overhead too
You can also read the file, instead of copy/pasting them in.
@lethal orbit Wait how do import from settings cuz i tried the from django.conf import settings
and then from settings import BAD_WORDS
then its says an error
no
from django.conf import settings
if not any(True for x in content if x in settings.BAD_WORDS):
...
any idea why the following piece of code doesnt work ??
console.log(yargs.argv.$0);
by "doesnt work" i mean the value remains the same
i'm trying to write a little note app in nodejs(still learning)
i think this server is python only :-(
u can go offtopic channels maybe
how many members does this server have?
a lot
like?
i would post it in a javascript discord server but there arent many servers that are like this one
unfortunately
;/
but this channel is focused on 'flask, django, html, css, and js'
if this was for multiple languages it would be good in some way
so my question is not offtopic
i didnt meant its offtopic but
i ion think a lot of ppl here will answer
:-(
@acoustic oyster btw its somehow save the form
when i checked in the admin panel
el oh el
lel, there may be an error in my logic, one sec
I understand that there are plenty of reasons you would want to censor usernames, but that should be up to the user, not the framework.
thats true but atleast would make models to help archieving that
ยฏ_(ใ)_/ยฏ
It's honestly very difficult to achieve this....
This list check can be easily bypassed....
oh
basically, just remove the content.split()
but yeah, it is generally not possible to actually achieve a good censor, the best option is reporting abusive names. But no harm in learning this ๐
๐
Tiltting at windmills
if i improve in future i may improve that to catch more complex usernames
thanks guys
def signup(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
bad_words = ("shit")
if not any(item in bad_words for item in form.cleaned_data.values()):
form.save()
messages.success(request, "Account successfully created")
else:
form = UserCreationForm()
context = {"form": form}
return render(request, 'registration/signup.html', context)
@frozen spear I think this is better actually, this should actually work and I think is more intuitive haha
removed redundant loop and made clearer generator
Hi all! sorry if I'm asking this in the wrong channel, I just wanted to ask about some page / YouTube channel about web applications on Python. Thanks all!!
Hi all! sorry if I'm asking this in the wrong channel, I just wanted to ask about some page / YouTube channel about web applications on Python. Thanks all!!
Like... recommendations? Any preference? Django? Flask? Other?
any recommendations for async server frameworks?
preferably something lightweight like flask
aiohttp
basically the lightest of them all
Starlette or Sanic are slightly heavier but will probably be more performant
https://discordapp.com/channels/267624335836053506/630504881542791169/747552709355241583
@warped timber i did a bigger summary here for ASGI's ^^
@acoustic oyster haha thanks king
I struggled with that one xD
For some reason my model isn't setting a primary key for entries, I have tried setting nothing, setting AutoField(primary_key=True) and IntegerField(primary_key=True) none of which work
For some reason my model isn't setting a primary key for entries, I have tried setting nothing, setting AutoField(primary_key=True) and IntegerField(primary_key=True) none of which work
@fair agate how do you know it's not setting a primary key
thanks cf8
ok. for me to process something after sending the page to the user, I would need to use a background task thing, like celery
ok. for me to process something after sending the page to the user, I would need to use a background task thing, like celery
@fair tide what framework are you using
flask at the moment
I was thinking I would render the page under an ID and then have a JS script grab data from another route to get some progress information
something like....
task_json = {}
# it'll be like {taskID:{'stage':"","percent":0}}
@flask_app.route('/generate/<id>`)
def generate(id):
# start background task to generate the thing, itll update task_json while its doing it
return render_template()
@flask_app.route('/info/<id>`)
def info(id):
return task_json[id]
and the javascript will get the json from the /info route and change the page accordingly
@worn wren here's the ideal place to ask about web development. People who are familiar with flask are most likely to hang out here
Does anyone know how I can access these items in my flask route? Trying to create a user likes/favorite feature. This is how my data is organized on the page, but the issue is that none of this is stored in a database, these are the results of a call to an api.
This is how my flask app route looks. Im not very versed in many to many relationships, but I have made models to store the items the user favorites. But, how do I access this directly off my page to use in my route?
I am using sorl-thumbnail to generate thumbnails in django. what does this @@property decorator do?
I know it creates thumbnail when image exists, but I dont understand how generator works... why not normal function? does it works automatically when image exists?
class SimpleAd(models.Model):
image = models.ImageField(upload_to='uploads/',
blank=True)
@property
def thumbnail(self):
if self.image:
return get_thumbnail(self.image, '50x50', quality=90)
return None
I am using sorl-thumbnail to generate thumbnails in django. what does this @@property decorator do?
I know it creates thumbnail when image exists, but I dont understand how generator works... why not normal function? does it works automatically when image exists?
@maiden kraken@propertyis essentially agetter. It's a special type of function that allows you to doad.thumbnailas opposed toad.thumbnail()(which isn't a very good method name).
It checks that self has an image attribute that is not NoneType.
Honestly, I feel like this should be done differently... generate the thumbnail once instead of calling return get_thumbnail(), but maybe the get_thumbnail function caches those
If not, it should
thanks for explanation. is property custom name or you can call it anyhow or are generators predefined? And do you know when the thumnail is created? Is it during object creation or is it during request for thumbnail?
You'd have to look into the get_thumbnail method to know that...
okay, get_thumbnail is a method from sorl_thumbnail I will not look that deep, that's not my level ๐
Generators in python are a different thing... functions that return an iterable, in simple terms.
okay thanks for help I will try to find more information about this topic on youtube
The property decorator is built-in. It's especially handy if you give a class an attribute, then decide to override it with a method down the line.
class Dog:
def __init__(self):
self.legs = 4
doggo = Dog()
print (doggo.legs) # prints 4
Then you decide to change the implementation....
class Dog:
def __init__(self):
self.amputee = False
@property
def legs(self):
if self.amputee:
return 3 # poor doggo
return 4
doggo = Dog()
print(doggo.legs) # still works as an attribute, even though it's a method
Just a quick question... Not sure if there's a better place to ask this but I want to write a Vue app using Python in the back-end, and I need websocket functionality in addition to my REST API. Originally I had thought I'd use the websocket module for the server, and Flask for the API, and just return a SPA with Flask, but now I'm seeing that Flask has the SocketIO package and that there's aiohttp web API functionality and I'm kind of torn between what I should use. Any idea on the best combination? I'd like to leverage async for the websocket portion of the app as I'm running subprocesses with asyncio and polling their system resource usage.
Discord oauth works on localhost?
Random Password Generator using Python3
is it possible to run django page not on the internet but inside local network? So every computer inside network will get access to it?
ex. if i run the manage.py runserver not on my pc but on server will it be available for every user?
Yes, but you'd have to set the ALLOWED_HOSTS setting. https://docs.djangoproject.com/en/3.1/ref/settings/#allowed-hosts
Still a good idea to run it in production mode with uwsgi or gunicorn, with DEBUG = False
Also, be sure to give the machine a static ip (and a domain name, if possible)
yeah, thanks a lot. I will not delve into much details because I am still a noob but that's very cool that you can do that
$ dig dev.patryk.tech
;; ANSWER SECTION:
dev.patryk.tech. 1798 IN A 192.168.43.77
^ I can visit dev.patryk.tech from my network.
ah okay, so you are making "custom" domain which send you to server ip?
and in the ip it's django server running
yup
yeah, will definiteley check it out, thanks a lot man you're lifesaver
Hello again. Django user here. I have this 3 properties inside my model:
id = models.AutoField(primary_key=True)
main_number = models.CharField(max_length=1000)
prefix = models.CharField(choices=PREFIX_CHOICES, max_length=100)
How do i define a method which does something like
main_number = id + prefix
How can I delete the whole model classes afer being migrated has been applied?
well, you can delete the model from your models.py and then upgrade your db
How can I implement one to one relationship in django model?
I want to set use can vote only once.
Should I use ForeignKey(unique=True)?
I don't think you have to change the model if you want the user to vote once. You just have to use some logic where you recorded their vote check if they have voted already or not
How can I implement one to one relationship in django model?
I want to set use can vote only once.
Should I use ForeignKey(unique=True)?
@prisma jackal depends on how your models are set up
@vestal hound General, I have post model, comment and answer model. Someone who has posted the post should allowed to vote. Other users than owner of the post are allowed to vote only once. That's all
then where are you storing the vote
@vestal hound I have model for voting
huh
you didn't say that earlier
so how many models do you have...
also don't tag me, thanks
People are different
is openAM a good way to store user account info for a website?
Hi
Does anyone know how I can access these items in my flask route? Trying to create a user likes/favorite feature. This is how my data is organized on the page, but the issue is that none of this is stored in a database, these are the results of a call to an api.
@zealous cloud it really depends on how you models.py looks like. I really reocmmend this tutorial https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-viii-followers
How can I implement one to one relationship in django model?
I want to set use can vote only once.
Should I use ForeignKey(unique=True)?
@prisma jackal I never tried Django but I think you should do that validation in your back-end.
If you have aclass Voteassociated with aclass Userall you have to do is query if there are any Votes associated with a certain user, if it is, you would not allow them to access the cast vote page. Theuniqueattribute may help you, but I'm really not sure it will
Hello again. Django user here. I have this 3 properties inside my model:
id = models.AutoField(primary_key=True)
main_number = models.CharField(max_length=1000)
prefix = models.CharField(choices=PREFIX_CHOICES, max_length=100)
How do i define a method which does something like
main_number = id + prefix
@maiden kraken Not sure, but I'd guess something like:
class MyClass():
# [...]
@property
def main_number(self):
return self.id + self.prefix
What kind of things you can do with async in a web app?
@weary dragon you mean asyncio?
yes
Your just asynchronous requests as a general concept
Never used it, I use threads to make asynchronous requests, everytime I encouter a asyncio snippets of code I leave it understanding less then previously
yes, but i want to know what kind of stuff you can do with it
like, until now i didn't need to use it
do you guys get someone else to do the front-end ? I love working with Flask/Python, but when it comes to doing the front-end I give up. I do not like working with CSS at all
I have so many cool projects, yet don't finish them because of the front-end
@weary dragon Assume you have 500 users/minute on your web app and they have to fill a contact form. As soon as a post request occurs it will trigger send_email() to your contact@ajxshero.com mail.
I think that would be a good moment to implement async requests
but I don't know, my understanding of async is pretty much mixed with threads
thanks, i think it's a good exemple
I just feel like using threads whenever my app triggers something that is irrelevant to the user, but if that routine is not done, it would mess up the user experience
and that's a must know for a web dev?
another example I use threads...Whenever a User POST a Form demonstrating interest on a product, I send their data to a CRM platform and then show them a thank-you page.
If for some reason I don't use threads and the process of integrating with the CRM fails, the user will never see the thank-you page
So I just make the process of pushing that data to the CRM a thread and redirect the user to the thank you page.
Asyncio with web systems are the most perfomant servers in general
For pretty much every webserver the asyncio approach will out pace a sync one
and what other advanced stuff are good to know
to make a great app, i learned basics for flask and i want to make a next step
Ajax, wasm, rest apis, websockets, caching, database interactions, scaling, etc....
ok, i will take a look, thanks
there is a way to use find_element by a position? Using webdriver. I have a table in a website that everytime I open, it changes the order of the rows in the table
Hey, guys I am pretty new flask and python I have been doing my first project the basic blog can anyone explain my backref in flask sqlalchemy I have read the documentation and other stuff i am a bit confused......
@sinful mantle Try pseudo-classes: :nth-child, :nth-last-child, :nth-of-type, :nth-last-of-type, :first-child, :last-child, :first-of-type, :last-of-type
Django, how do I get an object just by having the object's ID?
@native tide my_obj = MyClass.objects.get(id=1)?
Oh wow I'm an idiot, I forgot to add the .objects.get part. smh
does anyone here know javascript?
maybe 
maybe?
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
let a = document.links;
Array.from(a).forEach(function(element){
if(element.href.includes("google")){
console.log(element.href);
}
});
is this ok?
If it is small, just use
*<programming language name here> <some code here> *
to post your code
oh ok
oh
var alice = "this is some text";
console.log(alice);
oh i did not know you could do that
cool
If someone can help me in #help-donut
Am I right in saying Django is more popular than Flask, there are more job oppotunities?
it doesn't matter tbh.. In web development, every single language has more or less quite many job opportunities.
yea, since Django is more popular than flask, it may or may not have a job opportunity. But there's definitely a good amount of job opportunities for both.
Yeah, thanks for that. I'm thinking of moving to Django but boy is Flask nice.
Also is it possible to use postgres DBs with SQLAlchemy?
Jquery?
Hi, this my dockerfile for flask app I'm making. Is it possible to add postgres to it?
i would use docker compose for that
I'll check that, thanks
I have my_app/templates/my_app/base. html
my views.py lives inside my_app same folder with template. Can someone explain to me how View.py can see base.htm, because in my view.py I wrote something like
#some logic goes here.
return (request, 'my_app/base.html, context)
I wonder why does it work properly, my mind says you should write
template/my_app/base.html
In the above snippest function.
Hi guys, after submitting a form w/ flask, how can I refresh the page?
@prisma jackal I'm assuming you're using django
@versed python exactly
if you look at setting.py, there will be a dictionary, one of whose keys will be called template_dirs
it will have app Dirs in it
I am not sure about the names but I will try to explain what happens under the hood.
Basically when django is running on the server, it collects all the template folders (which can be configured via settings.py, i dont remember the setting name though) into a single folder from which it serves all your html files
for example you have two different apps called posts and registration and have two different html files in these under posts/templates/posts/home.html and registration/templates/registration/login.html. when django servers these html files it "collects" them into a virtual templates directory and which has a files structure like this
-- django-virtual-templates-directory/
-- posts/
- home.html
-- registration/
- login.html
So when you write something like return render(request, 'posts/home.html', context) then you get the correct html file that you requested for.
hope i was clear
@prisma jackal
@versed python yeah, thx
here's the settings i was talking about
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.media',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
notice APP_DIRS: True. that does the trick
@versed python so, the folder my_app\template (this should be named template) \base.htm?
if you write return render(request, 'my_app/base.html'),the django virtual template directory will be like this
django-virtual-template/
base.html
- posts/
- home.html
[..etc..]
@prisma jackal
and it should be named templates not template
Thx
Hey guys can anyone refer me to a Flutter discord community, I'm trying to deploy a TF model on an app and starting to learn Flutter by doing
from the flutter website: https://discord.com/invite/N7Yshp4
(if this breaks a rule, lmk)
why does css never update ;-;
yeah haha, I change something in the css files, but it either won't change on page or takes 50 tries lol
yeah haha, I change something in the css files, but it either won't change on page or takes 50 tries lol
@hallow jacinth use shift + F5 to load your statick again
static*
oh that worked, ty, didn't know I had to do that if I saved and reran server
Ctrl-F5 is hard reload - it tells the browser to ignore cache.
Otherwise it loads the old CSS files it cached the last time you opened the page.
anyone know why heroku logs is saying my db tables don't exist? I wrote the procfile to update db, but for some reson it won't
@hallow jacinth perhaps you have made changes to your local db. But u have to yet init the heroku db in the console
How these work . modelname_set in django?
hello! I'm unsure if this is the correct channel to post in since I'm new. I'm having difficulty with an app I am making and I believe the issue is database related...
I'm using SQLAlchemy and Flask to make a DnD character creator, and whenever I submit the form to create a new character, the rendered html template that the form redirects to does not display the new character.
@hallow jacinth im really not sure cause Im still about to implement my db on heroku as well
But Miguel Grunberg has a tutorial section about it
You can check that out
well I am pretty sure I followed it step by step. I actually redid the steps like 3 times, but still get the error
so I think I am just missing something somewhere
but I can't figure out what haha
Hey, so whenever a user fills a form it creates both an object and a group with the name the user entered, now I already made it so the user will 'join' the group automatically, but I don't know how to connect between the object and the group, I want to get access to the object details by only being in the group basically.
(Django)
Hey, so whenever a user fills a form it creates both an object and a group with the name the user entered, now I already made it so the user will 'join' the group automatically, but I don't know how to connect between the object and the group, I want to get access to the object details by only being in the group basically.
(Django)
@native tide Is there a way to like adding a list of users to the object instead?
here's my most recent commit
and sorry, what do you mean by "paste bin"?
How to get duration, like this post was posted 2hrs ago in django?
@dense bear pastebin.com.
On your characters.html, as far as I'm seeing it, I can't see you rendering the parsed characters object.
I added a โdescriptionโ field, but this came up
Did you runpython manage.py makemigrationsandpython manage.py migrate?
Something like:
{% for character in characters %}
<p>{{character.name}}</p>
{% endfor %}
omg thanks I got it to work
new_chars is not set
i dont know why i was passing the form variable
you have never parsed any objects to new_chars
should have used the query like you said
django-tables
with Django filter integration
packages
that you can use with django
Hello, I checked with the general channel and they suggested I come here for my question. Please let me know if there is a more appropriate channel.
My goal is to have a script that can access an FTP server and download a file from the FTP to the local disk.
I've been searching online for a few days and am pretty stuck. I can successfully login to the FTP and change directories, and view files in the directories. However, I cannot figure out how to fix the error I am getting when running the retrbinary method.
I created a pastebin- https://pastebin.com/wxDbbMNz
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
How <div></div> works?
It's just a page (sub)division...
By default, it makes a block with line breaks before and after (similar to a <p>).
But you can override that, and use it for very advanced features like cards, menu entries, etc.
Not something I can summarize easily...
How do I display products โside by sideโ? When I have โdisplay inlineโ, it displays my 2 text fields inline as well
well I am pretty sure I followed it step by step. I actually redid the steps like 3 times, but still get the error
@hallow jacinth I usually get that problem when making changes to the DB, sometimes you might need to delete old migrations, sometimes you might need to delete just a single python file named something like22375924.pyinside migrations folder, but if all didn't work try deletingyour_data.dbfile and remove migrations folder.
would this be the place to ask about selenium?
@slow rampart probably
How
<div></div>works?
@prisma jackal I used it for nesting other elements or divs usually containers, it's usually used for nesting other things, that's why frameworks like bootstrap provide a lot of classes fordivinstead of other elements likeporspan
<div> its a pretty generic tag though, for semantic improvement of your code I'd review https://www.w3schools.com/html/html5_semantic_elements.asp cause there are a lot of wrappers that are less generic than div
okay so i will try to explain my problem as good as i can, and i havent used the selenium library before but i have googled this as much as i could before asking for help
I am trying to make my bot type into a text field, the text field has no id and the class is a random string, but when i try to use find_element_by_class_name() it returns with no element found
the placeholder is "Title" but i could not find anything about using xpath to find something with the placeholder in python, i found one about javascript but i have close to no knowledge of that so i do not know how to translate it to py
so my question: how would i go about inputting text into a textbox when i cant find it with selenium?
if someone has a reply, please @ me with a reply, I will try to figure this out for a bit
@slow rampart what's the website and what is the element you're trying to select?
reddit and i am trying to get both the title and content boxes
you want to type in the search input field?
'cause if that's the case it has the typeattribute of search
I just built this for fun in css and html. What is a good first back end project that will help me learn the ways
<div>its a pretty generic tag though, for semantic improvement of your code I'd review https://www.w3schools.com/html/html5_semantic_elements.asp cause there are a lot of wrappers that are less generic thandiv
@sly canyon Among all of them, I only usedtitleandfooter, I will re-check when I need.
I just built this for fun in css and html. What is a good first back end project that will help me learn the ways
@brittle halo is that thing under green button an image or something real?
titlespace = browser.find_element_by_xpath('input[@placeholder="Title"]')
is there a way to type into a text box using a placeholder text in selenium? it returns with element not found for every method i use
<textarea
maxlength="300"
placeholder="Title"
class="PqYQ3WC15KaceZuKcFI02 _1ec_Oj5SWdypd8L-VELKg- "
rows="1"
style="overflow-x: hidden; overflow-wrap: break-word; height: 38.994px;">
</textarea>
@danielcis that thing under green button an image or something real?
@wind escarpit looks like an image to showcase what his aio looks like
@slow rampart the only textarea seems to be the title
it looks like it was inspired by cyber aio
@Pinkie CreamPiethe onlytextareaseems to be the title
@sly canyonyea the body text is in a div
@slow rampart are you doing that in reddit.com or reddit.com/submit?
and to find the body area you can find it by the attribute contenteditable="true"
well in selenium, when there are nested stuff (elements inside one another), you start from top and then go down the rabbit hole, I once had to do it for bugcrowd.com, I failed, it was too much and element names were changing
maybe: driver.find_element_by_tag_name('textarea')
driver.find_element_by_xpath('//div[@contenteditable="true"])
i will try those
@slow rampart try this website if you couldn't solve it 0x00sec.org
if not i will try what kisho said about nested stuff
@Pinkie CreamPietry this website if you couldn't solve it 0x00sec.org
@wind escarpwhat do i do there