#web-development
2 messages ยท Page 41 of 1
via btc
but after buying will you assist me and help me to develop site
digital ocean via btc cost 15$ per month
You can cancel it then
digital ocean is costly.
You have 2 weeks or 1 month of cancelation period by law
You can do it for $5 at the cheapest
The thing you brought won't work
i knowbut digital ocean dont accept btc, they accept 5$ via card
i dont have card, i am a student.
My spidey senses lean towards you saving it from a couple years ago
Try vultr or linode
anyways, i will move to digital ocean
after i will get high traffic
which i am not sure*
$55 a year?
Add like $10 into vps account
And use it for a month to see how it is
What site is it
If it's a vps then sure if you really want to
Not sure why you're going for hostinger specifically
in Django, can I use {% load staticfiles %} in the base layout that I extend, and then use static urls in the children templates?
or do I have to load the static files in each childtemplate seperately?
Ok then
You can
what is the cli command to install python
sudo apt-get install python3
Research the rest for yourself
No clue on that
like on vps
Just do apt-get install python3?
i have to install python inside domain name?
No
or on linux system
Erm
In this tutorial we will give you a quick introduction to linux and linux commands for aspiring linux students.
Contents of this Course:
1 - Introduction to Linux
2 - Quick Overview of Linux Distributions or Distros, such as Debian or Ubuntu
3 - Using the Linux Terminal
4 -...
on linux systemm on vps
are u good in python?
Watch the video and practise some basic linux stuff
Domain??
This vps has nothing to do with the domain
@tranquil robin best way to know is to try
@steel tiger
need a quick help
i want to force flarum/public directory to be webroot
what i have to modify
No clue
But a word containing root and a public directory don't sound the best?
That doesn't look like a vps or flask or nginx though
Use nginx
Also why are you setting up the webserver now
Instead of when you finish the rest
Use nginx not apache, no reason not too
Thought this was the vps
@steel tiger Cancelled the account
so now, what should be my plan.
aften buying a VPS,
how will i start ?
Install nginx and add a "coming soon" website somewhere onto the domain
Then learn flask and make the website then upload it
You could maybe just stop the vps instance for now if you don't want a coming soon site
Costs $5 per month so may aswell save some money
hi i wanna visualise a algorithm in web, so do i create an api for the algorithm at the back end(python) and use react and other javascript for front end to visualise it or is it better to do the whole thing in front end??
It depends on the thing you'll visualise. If there's huge amounts of pixels will change per frame etc. it might be hard to do this from python to java. But if the algorithm works much better in python, you can do with it too
I'm also struggling with such a thing these days. I'm not that experienced too
like path finding algorithm, monte carlo simulation, recursive division maze stuff like that
oh i will try to make the api in python for bacck end then do the front end in react and typescrit and other animation framework i guess. THnx @astral gyro
It would work better if you do the algho with javascript too. But you better try first
Btw, let me know after you finished. I wonder if you have any issues
for now i wasnt sure about which one to go with but i guess i will go with the python and react with other js framework for now. thnx @astral gyro
You're welcome
@grim cedar i want to do it too.make sure to send me a link
sure bud
imma change my account
Can you recommend a cheap or free hosting service for a small flask crud app?
I was just looking at Digital Ocean for hosting something myself. Basic plans start at $5/month and there seem to be a lot of ready to deploy images to base your app off of
I didn't specifically look for Flask, but if it isn't one of the ready to deploy images I'm sure you can install it manually. Though you may want to double check that
@scenic sky try azure hosting service if u gonna work on samll flask project
its free
for what ur doing
hi guys
anyone got time to help me out?
popup_1 = self.driver.find_element_by_xpath('//*[@id="modal-manager"]/div/div/div/div/div[3]/button[1]')
popup_1.click()
for some reason it won't find/click the popup_1 element
I don't know, I haven't even used ubuntu before
I'm not even interested in web development but i need to work with javascript for a couple of project
isnt using typescript a better practice than javascript
ditch javascript haha
do you know about seting vps
i used ubuntu
iw ould recommend centos for vps even tho ubuntu is lot easier to use
i am using 16, do 18 is stable?
yea it is
is there any problem with 16
1 year
lts is usually for 5 years
16 is simple to use too
so there is no problem in using 16
u can upgrade it afterwards
debian is good ??but have u used debian before
i am asking about ubuntu
Do you guys know a kind of free hosting to run only a bunch of pything scrpits without any other data like images or databases
azurehosting @astral gyro
@native tide As i said, I haven't used ubuntu before and I'm not into web development
jsut go for 18.04 lts @native tide
minimal, vestacp, webmin?
is based on what u need tbh??
if u r not doing anything advanced
jsut go for minimal
go with control panel then
and create website like https://math.stackexchange.com
or stackoverflow
@astral gyro ye and u get 1 year trial
do vestacp , webmin are control panel?
and which cp?
if ur doing something not related to images or database and static try github pages @astral gyro
vestacp
@grim cedar alright, thanks
u can always add new features based on ur needs @native tide
i recmmoned u to go with minimal tho
its like control panel are for newbie
where u can control all ur services in one single location
have u done this before ??
you just said minimal.
okay
VestaCP is simpler and straightforward, but given the recent security issues at which the developers themselves admitted they have no clue what's wrong, I'd stay away from them.
saw this on reddit
hmmm they probably fixed it by now
tho
@native tide if u know how to setup everything that u want in ur vps than minimal it is bud
others are just providing u with interface to work on specific stuffs thats all
like webmin just providing u with web interface for ur sys admin stuffs
okay
@grim cedar after install CP , can i still setup everything myself
as required
cp has most of the things u need for ur vps
yea u can
jus install it
just create a local non root user and run dicourse on it
oh yea
and all that thing
Done
sweet
installed ubuntu 18 with vestacp
sweet ๐
make a website than ?
wait'
okay
what about using python in backend
what is the benefit of it?
and how do i connect with backend
@grim cedar
u dont have to use python for backend, just choose it based on ur needs
how?
like each language have their own perks
ye ofc
yea to log in
obtain ur csr from ur vps
ye login to ur ssh
ye so they already have that for u
but i wanted nginx as web server
u sud read docmentation just so u know what u can do with that software
@grim cedar
here
what is domain instances here?
I am trying to point my domain to my server
i have setup nameserve
wym
u see that www
with .xyz
its that
ftp with xyz
n other ip address
u change it to urs
so when u create ur zone file
what is hostinger-tutorials.xyz
yes i created
my file name
hostinger-tutorials.xyz
n in the zone file
give me some name?
its like the configuration file
lol up to u to decide
ucan use use own domain name
for tht
hostinger-tutorials.xyz
how do i delete this file
i am inside this file
nano hostinger-tutorials.xyz
i am inside this
okay
hackvoerflow-dns.xyz
i created this
@grim cedar now what i have to replace
what about domain instances
now add what u have to add
i think ur filename sud be hackerflow.net
better if u stivk ith ur real domsain name
ah okay
so wat should i replace
i have to replace all hostinger-tutorials.xyz with hackoverflow.net
;
; BIND data file for hackoverflow.net
;
$TTL 3h
@ IN SOA ns1.hackoverflow.net. admin.hackoverflow.net. (
1 ; Serial
3h ; Refresh after 3 hours
1h ; Retry after 1 hour
1w ; Expire after 1 week
1h ) ; Negative caching TTL of 1 day
;
@ IN NS ns1.hackoverflow.net.
@ IN NS ns2.hackoverflow.net.
hackoverflow.net. IN MX 10 hackoverflow.net.
hackoverflow.net. IN A 185.224.139.215
ns1 IN A 185.224.139.215
ns2 IN A 185.224.139.215
www IN CNAME hackoverflow.net.
mail IN A 185.224.139.215
ftp IN CNAME hackoverflow.net.```
in CNAME
do i have to replace with?
hackoverflow.net(dot) or hackoverflow.net ?
@grim cedar
yup
i will probably pass out its almost 1 am. so i guess u gotta find someone else now gn bud
answer this is last
hackoverflow(dot)net(dot) or hackoverflow(dot)net
@grim cedar ?
hackeroverflow,net
ok
guys is there a way in django to query a db foreign key using the string value of the attribute instead of the id?
class Menu(models.Model):
item = models.CharField(max_length=30)
category = models.ForeignKey(
Category, on_delete=models.CASCADE, related_name="menu_category"
)
sprice = models.DecimalField(max_digits=4, decimal_places=2)
lprice = models.DecimalField(max_digits=4, decimal_places=2)
using Menu.objects.filter(category="pizza") doesn't work, I have to do Menu.objects.filter(category=1)
@tranquil robin
how
named-checkzone hackoverflow.net /etc/bind/zones/hackoverflow.net
no ttl specified: zone rejected
How do I filter out already taken foreignkey or OneToOne objects in django.
#models.py
from django.db import models
class Appointments(models.Model):
date = models.DateField(unique=True)
time = models.TimeField(unique=True)
class Booking(models.Model):
Appointment = models.OneToOneField(Appointments, unique=True, on_delete=models.CASCADE, error_messages={'unique': 'This time has been already taken, please choose another time.'})
firstname = models.CharField(max_length=150)
lastname = models.CharField(max_length=150)
email = models.EmailField()
number = models.IntegerField()
message = models.TextField()```
Now it only returns that error message, when time is already taken.
I am thinking about checking if there's Booking object which has id of the Appointments object and if it matches it won't let you take the Appointments time
hi y'all im delving into web dev atm and I was wondering what the best way to manage js dependencies is? I have been using cdnjs to import the libraries I need but I think that I want to move to something like NPM but rn it doesnt make sense how that fits in? I want something where I specify the libraries I want (package.json) and run a simply command to download and pack it into a single js file as if I had downloaded it manually and placed it in the assets folder. Is NPM the right tool here?
@steel tiger
I have bought VPS
and installed ubuntu 18.04
and running nginx webserver
and vetaCP
Ok
gosh has anyone done webhooks with twitch before?
I'm trying to do a subscription to a topic... and for all intensive purposes it looks like it works
but then if I check my app_token webhook subscriptions endpoint, I got nothing
what does this error means for django?
NoReverseMatch at /scripteditor/
Reverse for 'scripteditorView' with arguments '('',)' not found. 1 pattern(s) tried: ['scripteditor\/(?P<slug>[^/]+)\/$']
hmm I'm new myself. Missing the name attribute onthe urlpattern?
path('scripteditor/<slug>/', views.scripteditorView, name='scripteditorView'),
Im pretty sure the error is in the url, but idk what about the url is wrong
Virtualenv is robbing me for a week of progression
Anyonr using wsl for dev ?
Now i underatand why people just get macs
If you don't want to deal with it anymore you could run Linux in a VM
Anyway if you have a WSL question you should just ask
@vagrant adder went to sleep it was 6 am here
Virtualenv and packages
Cant seem to .ake it work for almost a week now ieven formated my disk and when i had fresh windows i managed my project to click ot was like after r days of trying and i just wanted to relax and left it all for almost 2 days
Then yesterday i was setting up postgres env vars i started to run into errors
I really cant think of anything except thst some package update messed things up , apart from that i use pycharm and ever since im running into errora. When i move my req.txt into folder pycharm recognize it and says packages x y are missing and u hit install . But right now it hust keep reporting only 2 packages
Idk is it possible but like there is some ghost venv over everything idk how to describe it im talking no sense prolly but i had my projects up and runing with 0 toubles since last week the only thing i did was upgrading pip in that period ... idk really clueless Nd lost ill try with wsl or just install linux on anothef hdd
All this means that i am doing something wrong but i use pycharm and create venv when needed actually i created 2 of em , one was for 20 lines flaks proje t just to see will my migrations work they did , and other one was from git pull
I know it something with me im not like oh this stupid machine what ever , but i cant seem to see what is causing this , like a 6 y old kid can create venv and install packages in it after 20 mins tutorial . I left the CMD way because i tough im missing something due to lack of "vizualzation" moved onto py charm i see every venv created all the packages inside , idk... Its something with SQLAlchemy , because all the other imports work as soon as i import my db , it says that modul doesnt exist . At first i tough im having some circular import , i spent a day trying to solve it . THen i just created new project with 20 lines , nah...
WIll make a final push today reinstall python ill use last req..text that actually worked and work my way up to see is there some conflict with package versions or something...
Everything seem to work fine when i use outdated packages..
Sorry its more of a rant..
it does get frustrating when you cannot solve something like this, and then it turns out to be something trivial and stupid that makes you wonder how you couldn't figure it out ๐
but best of luck finding a solution ๐
@tranquil robin yup...
please do not use that kind of language here @tranquil robin
sorry my bad
Yeah i think its something with version of packages , because it works fine if i use old ones . Syntax errors are not possible becuase im running a basic flask app 10 lines of code and 3 files
aghahah
๐
โค๏ธ
Going to get some coffe @vagrant adder if u see anything that could make sense out of my rant , let me know dude i would appreciate it a ton.
@native tide i know for a fact that werkzeug 1.0.0 that was released 2 days ago is broken
Werkzeug is one of the foundation packages of flask
Going back to 0.16.1 did the work for me
So in your requirements.txt in the first line
werkzeug==0.16.1
Yes
Is it possible to make some type of website so lets say someone visit the site, then the python code gets the directory of the guy that visited the site? In my case I am making a site that goes to the visitors path and extract some local files there and send prints its content to the console.. is this possible?
No, for security reason, the web page doesn't have access to that sort of data
so there wouldnt be any other way to achieve this?
what about downloading a file automatically when someone visit the website?
You'd have them to download and execute a file
Thats ok enough, but it can't be done as a background process or something?
It doesnโt sound very legit, does it?
Youโd require a user input at some point anyway
Alright thanks
hy i need help in flask
!ask
Asking good questions will yield a much higher chance of a quick response:
โข Don't ask to ask your question, just go ahead and tell us your problem.
โข Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
โข Try to solve the problem on your own first, we're not going to write code for you.
โข Show us the code you've tried and any errors or unexpected results it's giving.
โข Be patient while we're helping you.
You can find a much more detailed explanation on our website.
hey
what is my mx record here
i added dns zone file in my vps
;
; BIND data file for hackoverflow.net
;
$TTL 3h
@ IN SOA ns1.hackoverflow.net. admin.hackoverflow.net. (
1 ; Serial
3h ; Refresh after 3 hours
1h ; Retry after 1 hour
1w ; Expire after 1 week
1h ) ; Negative caching TTL of 1 day
;
@ IN NS ns1.hackoverflow.net.
@ IN NS ns2.hackoverflow.net.
hackoverflow.net. IN MX 10 hackoverflow.net.
hackoverflow.net. IN A 185.224.139.215
ns1 IN A 185.224.139.215
ns2 IN A 185.224.139.215
www IN CNAME hackoverflow.net.
mail IN A 185.224.139.215
ftp IN CNAME hackoverflow.net.```
to add in cloudfare
@tranquil robin
MX is for mail servers
so you need to know which one is your mail server
Why shouldn't you be able to?
@tired root yes
?
You need a smtp server
So unless your domain has one, you need to set it up first
But you only need MX for receiving
also, sfp records
otherwise you'll be blacklisted
yes
do i have to setup smtp server on VOS
VPS
my vps is running apache2 with php7.2
ubuntu 18.04
how to set up smtp server
install one
and do i have to add/edit mx or spf record on dns zone file
i dont see
can u show me
;
; BIND data file for hackoverflow.net
;
$TTL 10800
@ IN SOA ns1.hackoverflow.net. admin.hackoverflow.net. (
1 ; Serial
3h ; Refresh after 3 hours
1h ; Retry after 1 hour
1w ; Expire after 1 week
1h ) ; Negative caching TTL of 1 day
;
@ IN NS ns1.hackoverflow.net.
@ IN NS ns2.hackoverflow.net.
hackoverflow.net. IN MX 10 hackoverflow.net.
hackoverflow.net. IN A 185.224.139.215
ns1 IN A 185.224.139.215
ns2 IN A 185.224.139.215
www IN CNAME hackoverflow.net.
mail IN A 185.224.139.215
ftp IN CNAME hackoverflow.net.```
what is my mx record here
there is none
oh there it is
why are you asking if you know it is there
Anyway, you need to run an actual mail server and that isn't easy
as I said, set up Postfix and spf records
spf is a TXT record in bind9
hackoverflow.net in mail server
and @ in name
@tired root ?
and i dont have any CP on my vps, where do i will receive email?
you need to install a mail server
If your mail isn't handled otherwise
But seriously, leave the whole mail thing to others
it's not as simple as it looks
You get blacklisted as spammer very fast, if your mx isn't set up properly
is that right
I don't know what they expect for name, I only know how to do dns with bind, because that is all I use
but it isn't a field I recognize
What scorcher24 said ... Mail is hard, pay someone else to do it
He isn't reading what we say, at least that is my impression
SO what are my options for cdn with pycharm community ?
Im kind aconfused it doesnt support it ?
Any Django veterans in here? Trying to pick someoneโs brain on best practices for setting a global/singleton class. I essentially want a computationally expensive class to be started ahead of time and trying to track down the best process for this
Admittedly Iโm new to Django but not new to Web APIs or MVC.
@still palm Hi, it may sound silly, but have you considered replacing the - in the posts with a _ to avoid them being spaced out?
why not leave the spaces in? What problems are they causing?
yeah but the alternatives might be worse
you probably have users who have those URLs in their bookmarks -- so sure, come up with a better way to make URLs, but keep those old ones active, and have them redirect to the better version
ah, well played
Are Starlette / FastAPI / Quart / Vibora / Sanic better than Aiohttp? Should I consider migration to them?
if there is anyone well versed with flask-marshmallow, i'd appreciate if i can use your help on this stack overflow issue
hi, is it the right channel for Azure cloud service discussion
probably can't hurt as long as nobody else is talking
what are yalls thoughts on just py?
856 votes and 185 comments so far on Reddit
never heard of it
@brisk spindle fastapi and quart are the ones i've heard of
Quart is nice to work with
And it supports virtually all flask extensions
Low data mode?
no
i tried to install flarum
and then ssl
after then it is happening
ssl using letsencrypt
i am using cloudfare
Your server is offline right now
why
my apaceh2 is running
root@hackoverflow:~# sudo service apache2 restart
root@hackoverflow:~#
what is this file?
000-default.conf.save
There could be a lot of reason why you canโt connect to the website
is
do i should delete 000-default.conf.save
No
Try the http url
If you get the source html and display it on your computer, what does it look like?
it is on vps
You can use tools like https://transfer.sh to get the source on your computer
We were unable to find a vhost with a ServerName or Address of www.hackoverflow.net.
Which virtual host would you like to choose?
@jagged lark
Well, in which file is your configuration?
I mean, you put the configuration in a file, right?
And this file is in sites-available
I think you should delete default-ssl since you got rid of certbot
@jagged lark
i got a problem
if i type hackoverflow.net
my site show secure
but > if i type www.hackoverflow.net
it shows unsecured
Yes, because you got rid of certbot
i reinstalled it
Re-run the setup
ok
how can I pass class as function argument inside itself?
I have this function, so instead of add it to each class I thinking how to stay DRY
Hello everybody,
I am still kinda new but I managed to make an agreement with a business to build them a simple website with some functionality. I will do it with Flask and I will use some common libraries/packages. ย I would go for the paid $12/month package, although I still have some questions:
-
The app needs to send like a confirmation email. I've read that SMTP is not functioning or is blocked in Pythonanywhere? How can I understand this?
-
Is Pythonanywhere maintenance free? In the sense that I do not have to do any server maintenance or update? This might be one reason that is appealing over a droplet at DigitalOcean.
-
Is Pythonanywhere generally used as hobby place to host Flask projects or can it surely be used for proper and serious python apps?
Thank you in advance anybody who took the time to read and answer me! Have a nice day!
Did your client force you to go with pythonanywhere hosting solution? Digital ocean, linode and gcloud have cheap hostings too
Hey saki, no - I have free choice. I don't mind about the price, I just wish to have a very easy and reliable server in the long run
With digital ocean, all server configuration, maintenance and updates have to be done by me - and if there is a solution I could avoid dealing with the server, then it would be perfect
No platform does maintenance with such a low $/month
can I ask somthing about an error I get or this channel in use?
Sure, just let us finish @pliant falcon
ok sry
@native tide , i just finished a graphql api which is hosted on gcloud and their dashboard and options are extremely good for money i am paying
Linode and google have an api which you can use to see your server's uptime and such info
You are gonna have to set firewall rules and nginx manually but i don't mind that
Gcloud? I will check it out
But that means that with any option I still have periodically server work to do, right?
Sorry if this is a stupid question, but is my source for my flask app secure when hosted for free on heroku? There's no way people can access the actual source application or directory, right?
Nope, it's secure
I have a Django application with a page that contains many different products.
I want to have a modal that appears when the add button of a product is clicked, so that the user can choose the properties of the products and add it to the cart.
I have about 50 products in the page, and I need about 3 different modals for 3 different product groups.
what would be the best way of doing something like this?
@tranquil robin Javascript
Append the html for the modal at the end of your page, with visibility hidden. Then show it on your page, load content with a xhr
That is the canon way of doing that
so i would create a django view, that accepts a request and returns the required database info to JS.
then JS will modify the modal according to the information I received using Handlebars or something similar?
whats handlebars? I've never used django, but if you wanna do it without a page reload, that is the way of doing it
handlebars is a JS template, like Mustache
Yeah, I don't use these things. I write it myself.
makes smaller code without surprises
what do you mean you write it yourself?
you write the html creation inside JS instead of replacing in templates you mean?
I write my own js code, I don't use libraries
I don't get what you mean by that ๐
The information you need is in my first answer. If you want a dynamic modal, append the html to the page and show it as needed and load the content with a request from javascript
how you implement it is up to you
Hey guys, I'm kinda stumped. I'm working with the bottle framework for a university course project. I'm trying to set cookies (there is a bottle function and tutorial for that, so thats ok) but also adding the cookie data into a database as they are handed out, from which I can presumably count visitors and show the stats on a page and greet the visitor with a cookies information popup or a simple greeting popup if they visited before while showing their visit count. I'm using HTML, CSS and JS to build the website and SQLite to manage the database. My skills with each of these are rudementary at best and the tutorials I find for things like this are always with PHP or jQuery, but I was hoping to stick with what I'm sort of familiar with and not having every other line of code in a different language. Any thoughts/ideas or good resources to point me in the right direction? Thanks in advance โ๏ธ
Ok nevermind, SQLite is already causing issues. It says the tables exist but I cant see them in my SQLite browser. guessilldie.jpeg ๐คทโโ๏ธ
I need advice, i wanna have a "search" page on my flask app. So users will have a little html page with fields that you can enter like idk "Max number of potato" and "Color : red". Aim is to search my db to search things that match that criteria.
I was wondering on best way to do it
I was thinking of having js code that send a request with json, parse it manually or via marshmallow and give it to a function that will then search my db
why? just use a form, and POST the info to the same route
Is it doable /sane ? Idk much about all the things i said and i see that there is many options
I was thinking that configuring each field in both html, my flask route function then searching function woule be more work than parse a json
And also, to learn new stuff
For now i have 5/10 criterias but i would want something that i don't have to chnge too much if i have 20/30
with a form you will only need to add the fields you want, so its scalable
anyone know of any good sources for learning django rest api?
@marsh canyon youtube probably lol
What should you include or put in the home page
Its the first page the visitor sees
You will never get another chance to make a first impression.
Is there a way in django I can split a forms.selectmultiple into 2 or more separate dropdowns?
I mean, you could but I feel like if you need to do that there's something wrong in your logic. Why not have 2 or more selectmultiple ?
well I have an object Order that has one of its properties extra that is created with a manytomany relation, now if I create a form with a multiplechoice field, it gives all the items in 1 list or 1 group of checkbox, but I would like the user to be able to select the same entry in extra more than once if he wants
so i thought I could maybe split it up to several dropdowns
Oh, so you're not looking to split but to duplicate
you can think of it like a pizza, and you can choose the toppings. (toppings = extra). now maybe someone wants to choose mushrooms twice instead of being forced to choose mushrooms and then another topping because mushroom is already selected
I would do it with a formset. Add a topping = create a new form in the formset
ok, i willl check the formset out, thank you ๐
(flask)
Hello! I've been struggling to implement a file uploading feature to my flask project for days now. I've been able to upload files with a regular form but I need to do some form of file chunking since I want to accept really large files. Could anyone help me figure this out :3?
File chunking? If you don't want files on your server os, dropbox or boto3 apis are what you are looking for
The thing is that I do want them on my server, the project is a "personal cloud" or an interface for a nas at home
So I want my server to accept the files, store the file path in a db and then save it to a folder on a hard drive. I've got everything figured out except for the file chunking. A normal html form isn't capable enough since I want to be able to upload larger files than a couple of mb
AFAIK JavaScript allows accessing bytes of files you have picked using file input.
Plain HTML canโt do this.
Yeah I know
And I've been looking at a lot of different js libraries and stuff like that
But I can't find anything ood
good
And I can't find any good resources on how flask is going to stitch the file together when it's receiving the chunks
I am not not really sure where to put this, feel free to direct me! But does anyone know of a website or API or something, that I can pull updates on free games? like from steam, humble and epic? Preferably from one source. I know there's a few Python modules for getting Steam data. But I don't know any for Humble Bundle and EPIC Games. And those two sites, looks a like a massive main in the butt to scrape :S
@hollow glacier https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications you may start there
Files are simply streams of bytes, you can append to a file as you receive itโs parts
As I'm understanding it, this thing takes care of the "streaming"?
I just kinda need to follow the docs
So the xhr, filereader and File api and stuff does most of the work for me? Awesome!! I'm going to try this as soon as I can
But how would flask/python stitch togetehr the file?
some kind of file write function?
Yep, simply append to binary file every next chunk
fo= open("test.txt", "w")
filebuffer = streamthing
fo.writelines(filebuffer)
fo.close()
Something like that prbs
Be aware, there might be duplication or missing parts, always validate index of a part
wdym with validate?
โabโ instead โwโ
and f.write
If you have written first 23 parts of a file, you can append only 24th, not 56th nor 14th
well, technically speaking you can precreate huge file filled with zeroes beforehand
Then randomly write parts of it using f.seek
but youโll have to keep progress data somewhere
Uploading huge files over unstable channel isnโt easy
in django I have a form with 3 fields (name / address / number) is there a way to manually put each one of these fields in the template in html, instead of using {{ form|crispy }} ??
i tried using {{ form.name|crispy }} and the same with the other fields, but I end up with AttributeError: 'BoundWidget' object has no attribute 'field'
yes I read that, but its still giving me the same error
Because you can't use crispy when rendering forms manually
The whole point of crispy is to render a whole form according to a template for each fields
So you either make your own crispy templates or you render the fields manually without crispy
How can i add params the api reqeusts while using path()?
like /api/?name=john&?age=21
in django
more specifically
how do i set up my urls.py with path() to do the above
Hi, in Django where can I find the source of delete action intermediate page, I want to present all the affected records in the intermediate page when I disable a parent relation?
ok, I think I found it delete_selected_confirmation.html
I am trying to have google sheets trigger an on edit event in python. I have looked at this stack overflow question and I would like to implement the solution from the last answer. I am open to doing it another way as well, if you can think of something better.
https://stackoverflow.com/questions/38225812/gspread-change-listener
Copying from stack overflow this is the given answer:
In google apps script:
function onEdit (e) {
UrlFetchApp.fetch("http://myaddress.com");
}
And then in python after installing tornado
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
on_edit()
self.write('Updating.')
def on_edit():
# Code here
pass
app = tornado.web.Application([(r'/', MainHandler)])
app.listen(#port here)
tornado.ioloop.IOLoop.current().start()
I am very green on web stuff however, and I have a couple of questions:
How would I generate the URL address that UrlFetchApp.fetch() function uses? Surely it can't be localhost?
How do I decide what port to use? Is it arbitrary as long as I stay within the correct range?
Would I need to pay for a domain or something to have this working?
If you have any information that you think is helpful, please share ๐ Would love it if you can tag me with @twin thunder as well.
You know where I can get a mirror script for browser. Whatever moment I do on my browser will do it on the other
Guys, i am trying to figure out how to get rid of django-admin not found, i am on mac, i have django 3.0.3 installed, any idea how to fix this?
Just to make sure, you want to "remove" django-admin from your project ?
@late verge
If yes just remove the entry in settings.INSTALLED_APPS and the admin entry in your base urls conf
no i want to have django admin
when i do django-admin startproject testsite it says django-admin not found
@native tide ๐ค
Oh
Well you need to install django @late verge
Oh you said you have it installed, sorry. Are you sure you're using a python interpreter where it is installed though ? Like maybe you've installed it in a virtualenvironnment
i installed like in the official manual with pip
Are python libs in your path ? Have you tried logging off and back in ?
any one can provide any help with containerizing a django project with docker and deploying it up to AWS (not sure what is the best service to use)
in Django is it possible to provide a variable when creating a form form = Myform(variable="something") and use that variable to change the querysets of the form?
Note: Myform was created using form.ModalForm
Hey @tranquil robin - I think you should be able to do something like this:
class MyForm(ModelForm):
class Meta:
model = YourModel
def __init__(self, variable=None, **kwargs):
super(MyForm, self).__init__(**kwargs)
if variable:
self.fields['YourModel'].queryset = YourModel.objects.filter(variable=variable)
Maybe you could give it a try and let us know if that works for you^
@fickle wren I got past that part with the same solution you just provided.
but now I am facing another error -,-
AttributeError: 'CreateOrderItem' object has no attribute 'get'
Hmm in order to provide more help I would probably need to be able to reproduce this or take a look at your code
can you provide the traceback of the error message @tranquil robin
TBH I am not 100% sure how to help here - if I could reproduce on my machine I could probably mess around with it and figure it out but theres nothing thats standing out to me
I could link to my repo
sure let me DM you
Any source suggestion to learn django in the right way?
I just finished python course in school that cover def classes and recursion
the django website has a nice introduction
Ye I just saw that. tnx
Hi there, I have a question regarding Django ORM. I'm creating a demo project for my resume and was curious if such a relationship is possible to define when creating the models:
Especially since some of the relationships are "two-way" like Customer.jobs and Job.customer, the documentation only explains 'one-way' relationships. Doing this is quite easy just with some filtered queries, but I just didn't know if it is 'better' to just define these relationships within the models themselves, since there is a lot of overlapping data from connected models on each of the pages giving a detailed view on a given object/model. Thanks.
I hope the illustration helps more than confuses.
class Job(models.Model):
customer = models.ForeignKey(to=Customer, related_name="jobs", .....)
technicians = models.ManyToManyField(to=Technician, related_name="jobs", .....)
Didn't test but should work
@native tide
Hi, how can I add celery task to django admin.py ? as action?
I have task:
and now I want to add this to actions list:
I'm newbie in async so please help ๐
I'm wondering. Anyone willing to do some design review ?
I made a +-300 LOC website. I tried to do the simplest, most standard and with the less dependencies website with the purpose to test Django philosophy. I'm wondering if I made some major design errors. I'm experienced with Spring & Angular and I've been working with a custom python web framework for several months now so I'm not coming from nowhere but Django does seem different than what I'm used to.
Probably speaking of 15-30 minutes of your time. Of course I'll return the favor (Python, Java, SQL or whatever I may be able to help with).
I suppose I could document myself but that would take me tens of hours and I'm not sure I want to continue in this direction if it doesn't fit my needs and I already read so much documentation and I need human contact XD (my colleagues are robots).
Hmm sure but not now, am at work. Later this evening ?
Oh, that would be great !
@fickle wren I got past that part with the same solution you just provided.
but now I am facing another error -,-
AttributeError: 'CreateOrderItem' object has no attribute 'get'
@fickle wren figured out the problem, in case anyone wants so know.
In my forms.py while initializing the form I added an extra self -,- super(CreateOrderItem, self).__init__(self, *args, **kwargs)
It should have been like this super(CreateOrderItem, self).__init__(*args, **kwargs).
Thanks a wassem for the help ๐
Ofcourse! Glad to help @tranquil robin
@bleak bobcat Thank you very much, trying it now.
How can I save a visitors IP and timestamp to a variable in Bottle?
when using Flask and WTForms, is it safe to disable CSRF on a subform? such as:
triangle = FieldList(FormField(CET_Pair_Form), min_entries=3)
submit = SubmitField('Save')
class Meta:
csrf = False
side = SelectField(u'Side', choices=symbols, coerce=str)
ex = SelectField(u'Ex', choices=symbols, coerce=str)
Without csrf your site can be attacked with xss based attacks
the main form (CET_Triangle_form) still has CSRF, and form.hidden_tag() is used in the template. my question is for the subform (CET_Pair_Form)
the subform isn't ever used without the main form
Then you should be good
when I try to remove a form field in Django using self.fields.pop("fieldname") inside the form __init__() it doesn't remove the validation check for that field, which results in a false form.is_valid().
How can I remove the validation part corresponding to the field I am removing as well ?
Does someone have time to look at a stackoverflow question? Its making me crazy... https://stackoverflow.com/questions/60239724/reload-table-data-without-refreshing-the-page-in-django-and-jquery
Have you tried googling your error ? MultiValueDictKeyError try using request.GET.get('append_increment') instead, you should also pass a default value in case append_increment doesn't exists, like so : request.GET.get('append_increment', 0)
Have you tried googling your error ?
MultiValueDictKeyErrortry usingrequest.GET.get('append_increment')instead, you should also pass a default value in caseappend_incrementdoesn't exists, like so :request.GET.get('append_increment', 0)
@bleak bobcat Yeah, I thought GET.get was a typo though, I just tried it and I can access the page. But the main page is still not updating hmmm, but one step closer
Urgh, that didn't work as expected. Just creates duplicates. Anyone wanna help me out with two functionalities? $20 Paypal can be arranged ๐ DM!
What should my js look like if i want to create a navigation bar that appears when the scroll is on 1460px and above. And less than 1460px it disappears.
@native tide try the first answer in this post: https://stackoverflow.com/questions/15798360/show-div-on-scrolldown-after-800px/15800696
i'm still copy pasting in to my files
javascript things usually don't work when i do it
woo! it worked. lol thx
@native tide you're welcome!
can someone help me with HTML5
!ask
Asking good questions will yield a much higher chance of a quick response:
โข Don't ask to ask your question, just go ahead and tell us your problem.
โข Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
โข Try to solve the problem on your own first, we're not going to write code for you.
โข Show us the code you've tried and any errors or unexpected results it's giving.
โข Be patient while we're helping you.
You can find a much more detailed explanation on our website.
my question is
<svg width="500" height="500">
<path d="M 0 0 L200 200 L200 0 Z" style="stroke:#000; fill:none;" />
</svg>
how come they don't do M 0 0 L200 200 V200 0 Z
the only difference is V for the third
V instead of L
shape supposed to look like
Is there a tool out there that can help me blueprint a website design?
@fair comet I don't know if this is exactly what you mean, but you can search "website builder" on google, there are many different ones, This is one of them (https://www.wix.com/)
if i have this code ```HTML
section {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100vh;
background: url('/static/images/dreamcatcher0.jpg');
clip-path: circle(0px at center);
background-repeat: no-repeat;
}```
but i can't control the image
like make it responsive
No I don't know how
i'm afraid alot of things in my code will mess up if i put the image and the img tag. ๐
you can wrap it in a div and make that div responsive
<div>
<section></section>
</div>
and make the div responsive
Hi,
I'm using Selenium to fill in a form/field and then a dropdown list appears when I input the string and I press enter to validate the choice.
I used time.sleep(3) to make sure that the text is written before pressing enter (and it works).
But I want to switch to a cleaner way to do that and tried to implicitly wait but the button enter doesn't wait for the input and press enter too fast. When debugging, it works normally though.
Is there any way to make sure that the input is filled in before pressing enter ? (except for using time.sleep)
where there must be a validator in flask tehre is DataRequired
I am having problem regarding adding entry to a many to many relation field in Django. I have the models as follows
class Address(models.Model):
id = models.AutoField(primary_key=True)
country = CountryField(blank_label='(select country)', blank=False, null=False, verbose_name='Country')
state = models.CharField(
max_length=50,
choices=STATE_CHOICES,
verbose_name='State',
blank=False,
null=False
)
...
class Volunteer(models.Model):
userID = models.OneToOneField(User, on_delete=models.CASCADE, to_field='id', primary_key=True, related_name='volunteer')
identificationNumber = models.CharField(max_length=50, unique=True, blank=False, null=False, verbose_name='Identification Number')
currentAddress = models.ManyToManyField(Address, related_name='volunteerCurrentAddress', verbose_name='Current Address', blank=False)
permanentAddress = models.ManyToManyField(Address, related_name='volunteerPermanentAddress', verbose_name='Permanent Address', blank=False)
...
def save(self, *args, **kwargs):
self.slug = self.userID.username
super(Volunteer, self).save(*args, **kwargs)
And in the views, I get both the currentAddress and permanentAddress fields as a ManyToManyRelatedManager. They are temporaryVolunteer.currentAddress and temporaryVolunteer.permanentAddress. I use these to create a new Volunteer instance as
volunteer = Volunteer(...)
volunteer.save()
volunteer.currentAddress.add(temporaryVolunteer.currentAddress.all()[0])
volunteer.permanentAddress.add(temporaryVolunteer.permanentAddress.all()[0])
volunteer.save()
But when I do print(volunteer.currentAddress.all()) or print(volunteer.permanentAddress.all()), it returns an empty queryset. I also checked the admin site for confirmation and there are no entries of address on the volunteer instance. Can anyone please help me to add the entries. Thank You!
Can someone please tell me what's going on here?
[16/Feb/2020 20:41:35] "GET /package HTTP/1.1" 301 0
Internal Server Error: /package/
Traceback (most recent call last):
File "C:\Users\Skyler\PycharmProjects\junior-dev-reactor\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Skyler\PycharmProjects\junior-dev-reactor\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Skyler\PycharmProjects\junior-dev-reactor\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Skyler\PycharmProjects\junior-dev-reactor\app\packages\views.py", line 10, in index
for l in f:
File "C:\Program Files\Python37\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 6147: character maps to <undefined>
[16/Feb/2020 20:41:35] "GET /package/ HTTP/1.1" 500 100463
def index(request):
packages = {}
latset_header = None
with open("app/packages/status.real.txt") as f:
for l in f:
l = l.strip()
# if line contains a keyword
if "Package: " in l:
latset_header = l.replace("Package: ", "")
packages[latset_header] = {'name': latset_header}
elif "Depends: " in l:
packages[latset_header]['depends'] = l.replace("Depends: ", "")
elif "Description: " in l:
packages[latset_header]["description"] = l.replace("Description: ", "")
elif "Homepage: " in l:
packages[latset_header]["homepage"] = l.replace("Homepage: ", "")
context = {}
context['items'] = packages
return render(request, 'index.html', context)
Aah, I found it. The problem was that I had no encoding set for the file reader.
hey @tranquil robin
i did like this
section {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100vh;
background: url('/static/images/dreamcatcher0.jpg');
clip-path: circle(0px at center);
background-repeat: no-repeat;
}
.animated-bg-img {
width: 200vw;
height: 100%;
}```
<div class="animated-bg-img">
<section id="section"></section>
</div>```
its working?
you want the image to fill the section?
you can check css object-fit:
something like background-size: cover; background-position: center center;
But I may have the property wrong, google them
Hey
When there is an online learning series that divides the lessons in units
Should I take a school approach to this? As in self dedicate myself and design my own lesson plans?
Example: on this day learn this, on this day learn this
Etc
and make my own quizzes
Kinda like how school does it
Is this reccomended?
@true orbit whenever u are working through the lessons, try fiddling around with stuff and see what happens when you change something, and yes i would recommend you have some type of goal or schedule so that you can effectively complete the course
===================================
ok so i have built this ecommerce platform with flask for a product i'm selling, it uses the stripe charges API and delivers a digital product, the issue i'm having tho is my site at one point received a ton of traffic at the same time and i oversold stock because there were so many concurrent charge requests that were processing. i was wondering what the most effective way to control stock was so that i don't oversell. i tried doing it where the moment someone clicks purchase, stock is remove and then if their card declines or there is an error, it will add back the stock that was removed but was wondering if there is a more effective method for doing this
Ive got this CSS here, pretty basic for a button
button.menubutton {
background-color: #f8fcb5;
cursor: pointer;
transition-duration: 0.25s;
transform: scale(1);
}
button.menubutton:hover {
background-color: #e9f246;
transform: scale(1.25);
transition-duration: 0.25s;
}
However, upon hover-off, it just transforms instantly back to the initial stuff
How can i make a smooth transition back?
@haughty saffron try putting something like transition: .3s ease-in-out; in the parent element
ok
.btn-primary {
background-color: transparent;
border: 2px solid rgba(255, 255, 255, 0.9) !important;
color: rgba(255, 255, 255, 0.9);
font-family: "Varela Round";
letter-spacing: .15rem;
padding: 1rem 2rem;
text-transform: uppercase;
transition: .3s ease-in-out;
min-width: 10rem; }
.btn-primary:active, .btn-primary:hover {
backdrop-filter: blur(2px);
background-color: rgba(255, 255, 255, 0.9) !important;
border: 2px solid transparent !important;
color: #161616 !important;
outline: none; }```
this example would smoothly transition in and out of the active and hover states
nope
<!DOCTYPE html>
<html style="min-height: 100%;background-color:red">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>TBIH - Home</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<style>
.centered {
display: block;
margin-left: auto;
margin-right: auto;
width: 50%;
};
button.menubutton ::after {
background-color: #f8fcb5;
cursor: pointer;
transition: 0.25 ease-in-out;
transform: scale(1);
}
button.menubutton:hover, button.menubutton:active {
background-color: #e9f246;
transform: rotate(720deg) scale(1.25);
transition: 1.5s ease-in-out;
}
</style>
</head>
<body>
<script src="script.js"></script>
<header id="menubar" style="border-radius: 8px;border: 3px solid black;width:100%;background-color: #40ed9c">
<button class="menubutton" href="#">TEST BUTTON</>
</header>
<div style="background-color:red;width:100%;height:100%;color:white;font-family:monospace;align:center;text-align:center;font-size:32px">
Work In Progress!<br><br>You will not be able to see any content here for a while.<div>
<br><br>
<!-- <img src="https://media.giphy.com/media/NTY1kHmcLsCsg/source.gif" alt="Sad Face" class="center">-->
</body>
</html>
this is the html code
https://i.imgur.com/cCb3Ano.gifv is the result
button.menubutton ::after {
background-color: #f8fcb5;
cursor: pointer;
transition: 1.5s ease-in-out;
transition-timing-function: ease-in-out;
}
button.menubutton:hover, button.menubutton:active {
background-color: #e9f246;
transform: rotate(720deg) scale(1.25);
transition: 1.5s ease-in-out;
transition-timing-function: ease-in-out;
}
even with timing function its still the same
try something very simple like ```css
.menubutton {
background-color: #f8fcb5;
transition: 0.25 ease-in-out;
}
.menubutton:hover, .menubutton:active {
background-color: #e9f246;
}
Hmm you're right, let me see why mine works. 1 sec
<!DOCTYPE html>
<html style="min-height: 100%;background-color:red">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>TBIH - Home</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<style>
.centered {
display: block;
margin-left: auto;
margin-right: auto;
width: 50%;
};
/* button.menubutton ::after {
background-color: #f8fcb5;
cursor: pointer;
transition: 1.5s ease-in-out;
transition-timing-function: ease-in-out;
}
button.menubutton:hover, button.menubutton:active {
background-color: #e9f246;
transform: rotate(720deg) scale(1.25);
transition: 1.5s ease-in-out;
transition-timing-function: ease-in-out;
} */
.menubutton {
background-color: #f8fcb5;
transition: 0.25 ease-in-out;
}
.menubutton:hover, .menubutton:active {
background-color: #e9f246;
}
</style>
</head>
<body>
<script src="script.js"></script>
<header id="menubar" style="border-radius: 8px;border: 3px solid black;width:100%;background-color: #40ed9c">
<button class="menubutton" href="#">TEST BUTTON</>
</header>
<div style="background-color:red;width:100%;height:100%;color:white;font-family:monospace;align:center;text-align:center;font-size:32px">
Work In Progress!<br><br>You will not be able to see any content here for a while.<div>
<br><br>
<!-- <img src="https://media.giphy.com/media/NTY1kHmcLsCsg/source.gif" alt="Sad Face" class="center">-->
</body>
</html>
updated code
ill have to mystbin it soon
@haughty saffron seems that transition isn't compatible with all properties. e.g. this works fine html <!DOCTYPE html> <html> <head> <style> button { width: 100px; height: 100px; background: red; transition: 2s ease-in-out; } button:hover { width: 300px; } </style> </head> <body> <button></button> </body> </html>
but if you swap width for background it won't work
I'm sure there's a way to do it, my original example transitions background color just fine. Just can't figure out quite why ๐ฆ
@haughty saffron Might be because you forgot the unit of time
css has no idea if you're talking about seconds or ms
that will probably be why
I'll just settle with it being bouncy since unit dont work either
my example is probably inheriting some bootstrap properties that make it magically work
Any idea why this doesn't work then?
<!DOCTYPE html>
<html>
<head>
<style>
button {
width: 100px;
height: 100px;
background-color: red;
transition: 2s ease-in-out;
}
button:hover {
background-color: white;
}
</style>
</head>
<body>
<button></button>
</body>
</html>
Ohhhh I got it
can't use background-color: white;
background-color: rgba(255, 255, 255, 1); fixes it
ok hang on
in the <style> tag it doesnt work
but if i link it via <link>
it works
might have been a cache issue
Excuse me, everyone, is this the right place to make a question about GitHub?
- What kind of question
- If it's related to Python then yes and it's more suitable in #python-discussion channel.
- It's about making a GitHub page inaccessible, while keeping others visible/accessible.
- No, I believe it is exclusive to GitHub's functionalities.
Perhaps in one of the off-topic channels, #ot0-fear-of-python, #ot1-this-regex-is-impossible, #ot2-the-original-pubsta. Bonkers.
Thanks I guess
@cunning yarrow that isn't particularly possible without control of the backend, which GitHub pages doesn't give you
Hi pythonistas
Hi pythonistas
Here's the code of app.py
from flask import Flask,redirect,url_for,session,rend
from flask_wtf import FlaskForm
from wtforms import StringField,BooleanField,TextArea
from wtforms.validators import DataRequired
app = Flask(__name__)
app.config['SECRET_KEY'] = "sexyboy"
class InfoForm(FlaskForm):
breed = StringField("Which breed?",validators=[Da
submit = SubmitField("Submit")
@app.route("/",methods=["GET","POST"])
def index():
form = InfoForm()
if form.validate_on_submit():
session["breed"] = form.breed.data
return redirect(url_for("thankyou"))
return render_template("index.html",form=form)
@app.route("/thankyou")
def thankyou():
return render_template('thankyou.html')
if __name__ == "__main__":
app.run(debug=True)
index.html
<html>
2 <head>
3 <title> flask bootcamp </title>
4
5 </head>
6
7 <body>
8 <h1> Fill the form </h1>
9
10 <form methods="post">
11
12 {{form.hidden_tag()}}
13
14 {{form.breed.label}} {{form.breed}}
15 <br>
16
17
18 <br>
19
20
21
22 <br>
23
24 {{form.submit()}}
25
2631 </form>
32
33 <body>
34
35 </html>
No whenever I press submit ..the page reloads but doesn't take me to the thank you template..
Why is that ?
Got it 
Hi guys ive created a simple search function that my boss wants to put onto his webpage to help him and his staff. ive written it in python just wanting to know if anyone knows where i should be looking for information on making it compatible with html?
Your boss already have a webpage ?
yeah
page currently in wordpress, all i need to do is package my little code and file up so it can be inserted into page
i know sql works with html so i thought i could try get it through that way?
I want to create a directory website where users can add their own listings. Bootstrap for front end, python, flask and postgresql for back end. What do you guys think?
@narrow vessel joining the question I just started to learn flask.. so far I saw only forms, user management with python on a website.. is there an option to use my pure python script that do somthing different from other websites?
The universal solution would be to move your function to a flask app and make it return json then from your other website call your flask app with javascript
[Django]
How should I factorize CRUD links in a generic list view ?
{% extends "thrifty_app/base.html" %}
{% block content %}
<p><a href="{% url 'party_create' %}">Create a Party</a></p>
{% if party_list %}
<table>
<tr>
{% block list_header %}
<p>Developer must overwrite block named "list_header"</p>
{% endblock list_header %}
<th>Links</th>
</tr>
{% for item in object_list %}
<tr>
{% block list_row %}
<p>Developer must overwrite block named "list_row"</p>
{% endblock list_row %}
<td>
<a href="{% url 'party_detail' item.id %}">Detail</a>
<a href="{% url 'party_update' item.id %}">Update</a>
<a href="{% url 'party_delete' item.id %}">Delete</a>
</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>You have yet to create one</p>
{% endif %}
{% endblock content %}
You can see that I partially hardcoded links. I'd like to change that to be able to use template for other models.
I guess I could either:
- make a function / property with relevant available from the model
- inject relevant information in the context
But both looks like overkill.
I have a table on my webpage and I want to colour the text in cells in a certain row according to their text, whats the best way of doing that?
@tranquil robin Which technology ?
JS or JQuery are the 2 I know atm
I'd add a dedicated css class to relevant row using a conditional implemented in JS/JQuery I guess.
Loop on your table, find row, add class.
would that be better than changing the style.color of the cell?
yes because you don't need to dive into the code when you are changing it
It's also fine. I generally prefer having all style information in my css files but that might not be the best depending your scenario and it also depends your taste. At the very least, I don't have arugments against that.
Well, here is a better answer ^^
and please don't add jquery as depdency just for this... it is one line in js
oki
one more thing
I am comparing each cell to 4 different text values ( ex. Ready, Preparing, Broken ) is an if statement checking each condition the best way?
if text = ready:
do
elif text = Preparing:
do
elif text = Broken:
do
or is there a better way?
if text in [Preparing, Broken, ready]
yeah but if it is Broken it will be red, if it is Ready it will be green etc
but then you have only one code path
if you need multiple code pathes, then doing it for each is the way
@tranquil robin Do you have a backend on your website ? Where does the table content come from ?
the table does come from the backend
Then it would be a lot smarter to set the class directly from the backend
why is that?
Well, doing it in javascript means the client will have to do it, slowing down your frontend. Sure you may not feel it because you don't have a lot of records, but if you were working wih hundrer of thousands of records you would. You're already looping through your data when rendering the html, might aswell take the opportunity to set a class at the same time
How can I get to the level that I can understand what you saying guys?
@bleak bobcat but if its only about 10 or 15 items I guess it won't be an issue then?
no it doesn't
Then he is right, just use the jinja2 syntax to set the class on the backend
oki great, thank you both ๐
Even if the data was dynamic, it would be better to already have the class value from the backend instead of having a condition for every single entry
If the data changes on the frontend dynamically, using js is a valid approach
you spare the user the reload
And you should also spare the user's cpu hundreds of thousands of uncessary conditions.
Data can be dynamic/async while still coming with a class from the backend
I think you are wildly exaggerating the issue, but ok
I mean, there's other arguments for the backend to do the work...What if you wanted to add a new state other than Preparing, Broken, ready ? If javascript is the one doing the work you'll have to modify that there too. What if you forget ?
I don't think forget is a valid reason
No, but code maintenability is
ok you are right and I have my peace. You are just making things up now, but I am not going to argue
I have a question about Django ORM. How can I fetch rows following two relations between the same two tables ?
Ex. in SQL:
SELECT *
FROM transaction
WHERE transaction.buyer = current_user_id OR transaction.seller = current_user_id
ORDER BY emission_date DESC
Using the ORM, I can easily do user.sale_set or user.purchase_set but I need to merge the two, basically telling the ORM to do the above SQL query.
Can you show what your tables look like for Transaction and User (where the current_user_id is pointed to)
@dry pawn
I simplified a bit for explanation purpose. Transaction is linked to a model called Party which is basically the same thing as a User in this context.
class Transaction(models.Model, ModelSlug):
"""
The exchange of goods or services for money between two parties
"""
article = models.CharField(max_length=255, help_text='The exchanged goods or services')
payment = models.FloatField(help_text='The monetary compensation')
buyer = models.ForeignKey(Party, related_name='purchase_set', on_delete=models.CASCADE,
help_text='He who receives the article')
seller = models.ForeignKey(Party, related_name='sale_set', on_delete=models.CASCADE,
help_text='He who provides the article')
emission_date = models.DateTimeField('Emission Date', default=timezone.now,
help_text='When it was issued by its author')
And:
class Party(models.Model, ModelSlug):
"""
Someone that can possess, spend and receive money
"""
name = models.CharField(max_length=255, help_text='Easily identifies party')
Mmmh, I think it will be very simple after all, it's only a disjunction
You can usue Django's orm to fetch since you already in that.
from django.db.models import Q
Transaction.objects.filter(Q(seller=self.request.user.party) | Q(seller=self.request.user.party))
I don't know why it bugged me... It sounded more complicated at first.
That is the correct idea but I am not sure if thats technically correct. I understand you said Party is basically the same thing as a User but buyer and seller are not actually the user who is signed in right? Unless you have User related to party in someway that I am not seeing
@fickle wren The idea is that each User gets a Party that corresponds to himself. That party defines if a Transaction is incoming or outgoing.
I plan to either extends User (from auth package) so that it has that party attribute or add a one-to-one relation between Party and User (Party.user) that will only be fulfilled for instances that correspond to a User.
Said Party will be created when user register, along with the User.
Yeah, I gave some thought to that and I'm still not sure I like these solutions.
I plan to later on add a permission system to fulfill a feature where a User can manage several Party (your children, husband, wife, whoever). I'll think of a better solution at that point.
I was wondering one thing how safe is flask-session ? As far as i know its serveer based session ? And you could only see the token not the stuff inside of it ?
I want to create a directory website where users can add their own listings. Bootstrap for front end, python, flask and postgresql for back end. What do you guys think?
@kindred glacier listings of what?
@native tide session based auth is good if you have only 1 instance of flask app
if you have multiple, shard sessions between instances are not possible
that's where jwt comes into play
trying to config a pyramid app deployment to host with reverse proxy via nginx. I would like the app to serve from a base url like "https://site.com/app/" I have followed this resource https://docs.pylonsproject.org/projects/pyramid-cookbook/en/latest/deployment/uwsgi_nginx_systemd.html. so far I haven't turned anything up on how to configure the pyramid app to use the base url prefix
is there a header that I am missing, that should be passed along
In django, I'm using the shell to, on an instance of a model, call clean() then save(). This produces a different result from some code I added to those methods to when I save a model in the admin interface. I had thought that saving in the admin interface just called clean() then save(). Is this incorrect?
From what I can tell, neither .clean() nor .full_clean() are invoked when calling .save()
You can override save() to add them if you want, of course
yea, I manually call clean, then manually call save
Hi im trying to link my html file to my css stylesheet but when i go onto the html file it doesnt show red as the background (which is the background color) here is teh code
newbie here sorry
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="
../css/style.css">
<title>Website</title>
</head>
<body>
</body>
</html>
here is style sheet
body {
background: red;
}
@native tide Is the style.css in the static directory? Are you using flask?
What?
Are you using flask? Django?
