#web-development
2 messages · Page 124 of 1
Or locations.location
Its the same thing
I have tried the following as well, but it hasnt solved it:
choices=((1, 'London'), (2, 'Plymouth'), (3, 'Swansea'), (4, 'Birmingham'), (5, 'Manchester'), (6, 'Edinburgh'), (7, 'Belfast'))
"
Hi there
I just wanted to know if a request take long, are variables lost in flask?
@quick bay when you used the pasted choices above, were you still using ModelForm for your form?
Hello!
Quick question about Django apps. I've just create app using ./manage.py startapp tasks apps/tasks so I can gather all application in apps folder. But I don't know how to add it now to installed app
So i just thought id step in here and say web development these days is insane compared to wat it used to be... im using react, redux, REST, and DJANGO for my project. I dont remember js/php ever being this intense do do simple things. But it is what it is to have interactive parts of the website. Also you guys in here are all nuts. Said with love of course.
BEST?
I didn't set an admin username or password in my django app but the admin page is asking for my username and password. So, I can't sign into the admin page. How do I fix this?
go to your projects root directory, type "python manage.py createsuperuser". That should make an admin account!
Check out https://django-crispy-forms.readthedocs.io/en/latest/ . It gives you a lot more control of your forms on the front-end.
Sorry REST api
how can i make links for my images using flask?
we're talking about 1000+ images so gyazo/sharex/etc aint a option
@native tide gyazo provide api to get images url https://gyazo.com/api/docs/image
you can get url from response_body
oEmbed is really interesting as it provide embedded link
thanks!
Hi
I need help with flask
I have a post request method that get some text fields and file fields from a form and with that it creates a new .exe file
I would like to return this .exe file as a response in this post request
And then the user would be able to download it back from the front end
oh i see, do you mean saving the images file in your project folder?
if so you can use flask_wtf to save image to folder and save it's link https://flask-wtf.readthedocs.io/en/stable/form.html#module-flask_wtf.file
bro what should i prefer to learn btweeen these two,mongoDB and Mysql?
MySql better
okay so i should say mongodb fuck off right?
lets see some code
If i replicate someone else's cookie. will the server sent me data meant for them ?
I am positive the answer is a no.
How does server then verify that it's a different person
?
@near bison cookies are hard to get stolen because most browser has protection for it, also if you using ssl the cookies are encrypted so good luck decrypting it before the session is done. Cookies stolen are also called Session Hijacking you can read about it here https://en.wikipedia.org/wiki/Session_hijacking
In computer science, session hijacking, sometimes also known as cookie hijacking is the exploitation of a valid computer session—sometimes also called a session key—to gain unauthorized access to information or services in a computer system. In particular, it is used to refer to the theft of a magic cookie used to authenticate a user to a remote...
also this answer your question https://stackoverflow.com/questions/2498599/can-some-hacker-steal-a-web-browser-cookie-from-a-user-and-login-with-that-name
I am not the guy trying to steal. i am the trying to prevent that
i'm not referring to you, i just say possibility of it
Okay lol Thank you
Can't you just change your cookie, bruteforcing it until you get some sort of valid key?
that question better be asked in #cybersecurity
most of us don't work with encryption
https://github.com/milindmadhukar/site here, i dunno why my static files aren't loading (try going to the environment page).
@covert kernel the site look normal for me(no css breaking), the only thing can't get request are these
@covert kernel in your settings.py it's development or production environment? (tell by DEBUG=True or False)
development
DEBUG=True
@covert kernel open development console with f12 on browser check console and print out the error so we can see which path not working
have you tried running the django project after you forked it to see if the css breaking? i see a commit of you adding donation app
Thanks.
Guys can someone help me with flask it won't show images i have the static folder and everything set up? pls help
How are you accessing the image?
figured it out sorry @native tide
That's great!
can someone pls help me here?
thanks a lot!
can anyone help me with django development?
I am working with django channels to create realtime chat app
I am connecting to web socket from my react frontend. What I am currently doing is that when a user tries to connect to socket, after passing the authentication process, the connect method of WebSocketConsumer extract all thevhroups of users from the DB and add that user to all his groups (redis channel layers).
Can anyone suggest some optimal way that how can I determine which of that layer received the message and broadcast that message to that specific layer. If anyone has any other way of doing this, it will be highly appreciated.
Thanks :logo_django2:
can flask display images from different place than static folder?
Hi, any idea why am I getting a jinja2.exceptions.TemplateNotFound: giveaway.html error? (Using flask)
Code:
from flask import Flask, redirect, url_for, render_template, request
app = Flask(__name__)
@app.route('/test/<start>/<stop>')
def giveaway(start, stop):
return render_template("giveaway.html")
if __name__ == '__main__':
app.run(debug=True, host='localhost', port=2000)
Oh wait
I forgot to put the html file into the templates folder
However
My fonts aren't working correctly when I use flask
I'm using css and html and rendering the html template with flask
desktop > main.py and templates folder and in templates, style.css and html files
hold up
I'll try this out https://stackoverflow.com/questions/40013987/python-flask-not-accepting-custom-fonts
you need static
@font-face {
font-family: 'OpenSans-Bold';
font-style: normal;
font-weight: 800;
src: url('../fonts/OpenSans-Bold.ttf') format('truetype');
}
Would that go into my css file
This is my css file
Thanks!
I still need help with flask 😭
i made a website using a software i have all its files i changed the directories such that it gets the css and images from static
it works when i open it as html
but flask won't show images or css designs
yup you can do this in python pretty simple
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
elif num<str(smallest) :
smallest=num
elif num>str(largest):
largest=num
print(num)
print("Maximum is", largest)
print("Minimum is", smallest)
@native tide
whats the traceback
Oh and for the last two printing things I suggest using a f string
hey you can't us < on a string
@native tide Comparison operators such as < & > are not on str, only numbers
please can someone?
yup
Or you can check if it's a digit by using if num.is_digit():
yup but it's mentioned in the question to use try and except
Yeah, just went a bit off aha, my bad
largest = None
smallest = None
while True:
num = input("Enter a number: ")
try:
if num == "done" :
break
elif num<int(smallest) :
smallest=num
elif num>int(largest):
largest=num
print(num)
except : print("Number is Not valid ")
print("Maximum is", largest)
print("Minimum is", smallest)
i didn't succeed , although it looks logic for me !!!
did it give any error?
You are not allowed to use that command here. Please use the #bot-commands channel instead.
Nope , but it's not logic !!
hey the try and except is at the wrong place
use the try ad except before
wait
hi. i just finished a website using html and flask
does the website contain images?
largest=" "
smallest=" "
n=0
numbers=[]
while True:
num = input()
try:
num = int(num)
numbers.append(num)
n=n+1
except:
if num == "done":
numbers.sort()
print(numbers)
print("Max number is "+str(numbers[0]))
print("least number is "+str(numbers[n-1]))
else:
print("enter a number")```
review this code and find your mistakes @native tide
hey @native tide will you pls pls help me
i feel accomplished for getting django up quickly lol
ah yes
dude i ran djiango and flask But both require webdev skills , what is the point of using Python with them?
i mean using python with html/css and so on
does the {{url_for('static', filename='background7.png')} also fetch files which are ins static but inside a sub folder
u need python to process the content its way better done with python
so Basically
Html caintains CSS
and Python contain html ?
i mean it is Ok But Im not too good at webdev and i thought with Python i can take a shortcut But seems impossible
T_T same this is so painful even if i make a website using some app just integrating it into flask is straight up headache
bruh Im already giving up lol
i finished the whole backend in 15 mins T_T and i am stuck on the front end for about 3 days now and i havent figures out shit yet
i feel like i just make it harder for myself
backend is of course python
how are you so relatable 😦
lol dont give up - regroup and find a better way
is there a good way to do it?
- shrug *
hey u mastered flask help pls
wow nice
Oh no it's too late to do this
but i have no clue what im doing tbh hah just messin around
i can't even mess around properly with flask that's my PROBLEM
so far django make sense and seems pretty powerful
im just making a small web app to help make life easy at work
wow nice
flask made complete sense was pretty easy very cool i loved it until it won't show my images and css files and i cant configure it
maybe linking error
o_O
pretty basic question but
how does one use an insert statement, using flask sqlalchemy
like how does the orm know which column to add the values to
Hello everyone, i am facing a problem with django, can i ask you for some help please
sure
can i share some screens to explain my problem or some of my code ?
well i am working on a mobile app (in flutter) but for the admin panel i decided to make it in django (so i can learn more about this framework since i already code in python) but i can't do a feature with TabularInline so i decided to make a small new project to experience some of my code and i still face a problem, here is my code in screens (just admin.py and models.py)
but when i try to add a new question, it works correctly only if i don't add an answer too, and when i try to add an answer i got this error (it doesn't get the question)
and when i try to register a question with some answers, i got this error
sorry?
<h1><p style="font-family: 'Comic Sans MS"; color:Blue>40 days</p></h1>, only the font works, not the color, any idea why?
Hi can anyone help me with flask
@gleaming spire
<h1><p style="color:blue; font-family: 'Comic Sans MS' ">40 days</p>
I think you need to put the colour before the font
@astral river I don't know flask, but post your problem and when people will see it they will help
Oh
Actually I am making a machine learning application using flask for backend
Np
I make a post request with to upload two images and process them
But if the process takes too long I get an empty response
get_transfer_image:1 Failed to load resource: net::ERR_EMPTY_RESPONSE
This error to be exact
When the process does not take too long (I set the number of iterations to a lower value) it works fine
Can I just use another database with setting up another one in the settings and then call databases = {'other'} in the views file?
Hey @native monolith!
It looks like you tried to attach file type(s) that we do not allow (.log). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .webm, .webp, .flac, .afdesign, .m4a, .csv.
Feel free to ask in #community-meta if you think this is a mistake.
Hey @native monolith!
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:
Okey, once more, I got this weird endpoints, that somebody tried to check. Is it more likely to be human? or I got some bot crawling on my page?
I wonder if this is single guy trying, or there is more of them :'D, error is always 404 no matter what they are trying to do.
good I have only deploy key stored and not passwords there ^^
https://pastecode.io/s/Ppphyh65Ea
can someone pls help me here?
I've also added important information which I failed to fill-out earlier.
I have tried everything but using gunicorn to run web app of flask is somehow not printing anything! I tried buffered output flushing and all
also launching my app through wsgi.py works fine but through gunicorn wsgi:app it does something weird
or it is intentional, i don't know but i can't figure out what
how do i map my json mappping with the data of models and keep the same structure? https://gist.github.com/SkyBulk/52ccdab577c94bde399c3b6ae8288208
Yeah, if you have a web app or api online publicly, it'll get hit by bot scans looking for .env files, exes, wp-login, phpmyadmin, and more. Just part of running a service online.
I want to make a pwa for a program im trying to make, so my app has a python backend which im almost done with, i wanna know which i should use for frontend react or vue
really? 🤔
for .gitignore?
boys can anyone who use vs code share his settings
{"emmet.includeLanguages": {
"javascript": "javascriptreact",
"vue-html": "html",
"razor": "html",
"plaintext": "jade",
}
}
this is for the inbuild emmet and it seems to not work
Is it possible to create a valid XPATH expression through #document? https://gyazo.com/8baeeb60a68e5efd6ce0a4412087dcad
It seems really weird
Pardon?
Saw your logs. Lots of weird url hits yeah? 404ing?
Yes they’d scan for .gitignore to see if you published a whole repo. Then if they saw that the might start looking for other files containing secrets or other compromising files.
exactly! these are not good crawlers 😄, but I got only deploykey for pulling stuff ^^
Probably this issue is related to the request/response timeout
Could anyone help me figure out what #document here means?
And why can't I nest through it
#help-kiwi HTML help 😔
Hi
I need help here
Id need to use the value set to the variable outputFileName in another api method
How could I do it? Declaring it as a global variable?
yep global var
I don’t think you understand. They’re not really crawling cause they don’t know what you have to crawl. That’s the point. They’re poking you to see if they can find something they KNOW is related to something exploitable. So they’re not bad. They’re casting a wide net looking for things that might not even possibly be on your server. Automatically. They’re probably scanning thousands of servers at a time. This will happen to pretty much anything you expose online.
good bots?
not harmful? 🤔 ok
Hey sorry may I ask a quick web scraping question here? 😄
Don't know where to put this.https://www.youtube.com/watch?v=Ksq8K-ky-8I
Code and Diagrams at: https://www.elithecomputerguy.com/2020/12/arduino-raspberry-pi-web-based-fan-switch/
In this project we are going to use an Arduino to get the room temperature, and be able to turn on a regular house fan. The Arduino sends the temperature value to the Raspberry Pi using the Serial Communication, the Pi’s Python script take...
well hello everyone, i am trying to make a visualization of a picture on the admin-panel so i did this commands :
django-admin startproject imagevizualisation
cd imagevizualisation
./manage.py startapp core
then i added the 'core' on my settings, and i configured my database in the settings,
i migrated then with the commands :
./manage.py migrate
./manage.py createsuperuser
./manage.py runserver
after that i have an admin panel clean, and i tried to follow this tutorial so i just copy/past the code in this link
but i still have 2 problems : the first one is in VSC i have an error with as shown on the screen , and the second one is that the image isn't displayed on the screen as shown on the 2nd screen
@vernal furnace
@azure flax you problem is in this line of code,
upload_to='post/thumbnail/%Y/%m/%d/'
you don't actually have this destination
well actually the image is saved because in my folder (local) i have the photo saved
django created it
i guess its a good idea to store data without having it in 2 copys
oh nice
maybe i have to add some settings on my settings.py to authorize pictures to get plot?
lemme see
because when i checked the source code, the <img /> is made correctly but it doesn't appear
you don't need core.models just .models since both files are in the same folder right?
yes but it works fine even with it
yep
default='default.jpg'
can you add default.jpg under the same folder
make it the same picture, but it NEEDS to be called default.jpg otherwise it will not work
under post/thumnail folder add a picture called default jpg
and your imagefield should be like this
models.ImageField(default='default.jpg', upload_to='your destination')
@azure flax
look, forget everything I said,
okay
go to settings.py
rename your post/thumbnail folder to something like media
now go to settings.py and import os at the beginning of the file
how to do this please?
if u are using visual studio right click on the folder
at the bottom there's rename option
ah!
but i have to configure something with MEDIA = ..
non?
yes, do u did what I said?
yes but i don't find the configuration of medias in my settings.py
okay thank you
ok
now go to settings.py and import os
already
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
add these under ```python
STATIC_URL = '/static/'
last line
done
see if it works now
no it doesn't work
same problem?
yes
i am trying to run flask...i am using the offcicial documentation but it gves me an error...i am trying to run the "minimal aplication" i copied the code and tried to run it via export FLASK_APP=hello.py where hello.py is the name of my webapp in ipyb format (i am using vs studio code with a notebook extension)...it gives me this error:
PS C:\Users\Acer> export FLASK_APP=flask.ipyb
export : The term 'export' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
- export FLASK_APP=flask.ipyb
-
+ CategoryInfo : ObjectNotFound: (export:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
done
before upload_to add default='default.png'
still doesn't work
do u have a default.png in media?
I want to move all the auth stuff in django from one database to another is this possible when I just change the default database in settings.py and migrate?
@azure flax I found a solution
really!
urlpatterns = [
........
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
in urls.py
add that ```python
- static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
where?
this in the urls.py?
the main project urls.py
also,
make it like this
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
so thats how it should look
urlpatterns = [
........
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
@azure flax
now it must work
like it have no reason to not work lol
but i should import settings from the settings.py ?
from django.conf import settings
from django.conf.urls.static import static
these,
import these
nice :D!
@lethal cedar read this carefully, hope it helps!
I want to deploy my django project to the production environments, and associated it with an new empty database, and I did as follows :
Create an new empty database
Updated settings.py and pointe...
Thanks a lot man
Read the answers too, otherwise you will be in a huge trouble 😐
Yeah but I think I wouldn't have deleted the migrations
If I only want to move a part of the database I will have to set up two databases and then set the database for every model?
I guess the whole point of moving part of a certain database is to transport it to a new database right?
Yeah
If you don’t want every application to be synchronized onto a particular database, you can define a database router that implements a policy constraining the availability of particular models.
So basically this is what you want?
@lethal cedar
So listen, define a new database under the default one in settings.py
if u already done that type ok
@lethal cedar
now to migrate to a new database first
manage.py migrate auth --database=databasename
set your data base name instead of databasename
and now
python manage.py migrate app --database=databasename
app, is the app you want to migrate
Hm I got an error on the first command
OK that worked
so that's all you needed?
wait
Alright, so i want to do this:
1) Update local files from a git repo
2) Stop a service running my webserver
3) Install requirements.txt inside a venv
4) Start my webserver service
how would i go around doing this? a link to a blog/guide would be appreciated
im running a flask server with gunicorn
am on debian
@lethal cedar If u can be faster it would be better because I have to go very soon
Yeah sorry
I have it working now I think
I had to add a database router though
@vernal furnace Thanks a lot
how do i map my json mappping with the data of models and keep the same structure? https://gist.github.com/SkyBulk/52ccdab577c94bde399c3b6ae8288208
np
Hello everyone, hope everyone is okay!
I am working on a django project and i am doign the admin panel with django-admin and i was owing to make a custom filter with list_filter but i don't find any example on internet so i would like to ask you if someone did it before (a custom filter instead of the is true or not already available on the list_filter available on the django admin panel) !
thanks to everyone in advance for the help!
Anyone know why npm is recompiling code? Im using --watch it says it is, but it hasnt shown up when looking at it in the browser
@wicked elbow using create-react-app?
I solved it. Chrome was storing and reusing the js file instead of using the updated js file being compiled by npm on edit
Does anyone here use Flask?
$1 to anyone that can make a super simple web scraper for one website like I litteraly only need it to print one line of text from this website DM me
No such thing as a simple web scraper lmao unless theres an api involved
Is this the discord for django or just all web-apps?
import {getHistoricRates} from 'dukascopy-node';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:979:16)
at Module._compile (internal/modules/cjs/loader.js:1027:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
C:\Users\User\Documents\Programming\Python\Popo>```
What's causing the error?
Its in javascript btw
Code: ```py
// ES6 Import
import {getHistoricRates} from 'dukascopy-node';
// CommonJS
const {getHistoricRates} = require('dukascopy-node');
let instruments = ['FRA.IDX', 'EUS.IDX', 'DEU.IDX', 'FRA.IDX', 'BRENT',
'LIGHT', 'AUDUSD','NZDUSD','AUDJPY','GBPAUD',
'GBPNZD','USDDKK','EURUSD','USDCHF','EURAUD','AUDCHF','EURGBP',
'GBPCHF'];
getHistoricRates({
instrument: 'btcusd',
dates: {
from: '2018-01-01',
to: '2019-01-01'
},
timeframe: 'd1',
format: 'json'
})
.then(data => {
console.log(data);
})
.catch(error => {
console.log('error', error);
});
Hey. I have a question about react redirecting to a static page 404.html where index.html is in public directory. Basically I have <Route exact path="/404.html"/> and <Redirect to="/404.html"/> as a part of Router tags. When I type a path that doesn't exist. Why does /404.html path or any unknown path loads (index.html content without any component) before I can refresh again to see 404.html content?
Also, what is the best way to load 404 page or about page (completely different content ig) without navbar and footer? I already rendered navbar and footer in index.js including < App/> component. Is the method above better?
isnt that against ToS now?
You must not access Instagram's private API by any other means other than the Instagram application itself.
You must not crawl, scrape, or otherwise cache any content from Instagram including but not limited to user profiles and photos.
@trim marten
i think a dm bot would count as scraping
and maybe crawling depending on context
Did you find anyone?
Hey guys can anyone give django project ideas??
@barren swift Router renders a React component when you visit that route. You can't try to render a whole html page when you visit that route, because you're then trying to implement server-side-rendering which is a backend task.
So, you need to create a component for your 404 page, and have the paths as URLs not files.
<Router>
<Switch>
<Route exact path="/404">
<404Component />
</Route>
<Route exact path="/">
<LandingPageComponent />
</Route>
</Switch>
</Router>
Then use your redirect to go to /404 to render the 404 component, on index.html
how can I convert JSON file to make it use as a table in Django ORM?
@native tide are you making a request to your backend, with data in JSON format?
nope
Hello everyone, hope everyone is okay!
I am working on a django project and i am doign the admin panel with django-admin and i was owing to make a custom filter with list_filter but i don't find any example on internet so i would like to ask you if someone did it before (a custom filter instead of the is true or not already available on the list_filter available on the django admin panel) !
thanks to everyone in advance for the help!
Anyone familliar with stripe billing? How do i add payment methods to invoices?
ı have some problems
can anyone help me:
?
ı just broke up w/ my gf
but ı was doın' develope a website
that kinda web develope problem i think
just help
Hey so, I've started a chat website but I dont really have the brain to work out storing the chat messages when I send the websocket data
How do I make my cookies HTTPONLY? I looked through docs and found
SESSION_COOKIE_HTTPONLY = True
CSRF_COOKIE_HTTPONLY = True
But I am not sure what classifies as a "session cookie". do cookies set by Response.set_cookie() count as session cookies?
developing a website is not ur problem its ur grammar lol
jk you'll find someone better king
Get blogs entries with id 1, 4 and 7
Blog.objects.filter(pk__in=[1,4,7])
can I use a list to look up varies entries in JSONField ?
data__cities__contains='London', )
@fallen spoke I think so, have you checked by making those settings true, then inspecting the cookie set?
access=<token_value>; Path=/; Domain=127.0.0.1;
this is the only thing that is in the cookie. It does not say anything about being HTTPONLY
Hmm you may need some sort of plugin to check, I'm not 100% positive. Searching on stack overflow says that a HTTPonly cookie should be like:
mycookie=somevalue; path=/securesite/; Expires=12/12/2010; secure; httpOnly;
Hello, im struggling to get elements to line up/stay on the page, while scaling with the page.
In Django, is it ok to have one rather heavy custom User model (Employee, with cca 20 "columns") or is it better to do light model, for example only Username, name, password, and then have a one-to-one relationship to model Profile?
@upper heart You should (in most cases) use Django's User model, add some custom columns if you need.
I need to use username and password to log in. Also two custom login backends. Not email, so I went with custom user model instead. But I've put everything into one model and now I wonder, if it is better to split it up.
in terms of coding, it's easier to just have it all in one model, then you can just access the table's column instead of having to traverse foreign keys.
but in terms of performance, I don't know whether splitting it up would give any advantage, you should only probably worry about performance until you notice it.
for some reason I logged into pycharm now python isn't installed neither is any of my dependencies
wtf
Guys what do I need to learn in front-end and back-end web development???????
HTML, CSS, JS frontend Django Python backend o.o?
Ok thx you so much
easier, but not necessarily better.
I'd say it depends on whether all the columns apply to all possible rows (in this case, each user has a profile)
if so, that'd be preferable
but otherwise OneToOneFields might be appropriate
as for performance...whenever you combine results from multiple tables like that you need joins, which have a cost
so in that sense having all the data in one table is generally faster (look up database denormalisation)
the tradeoff is decreased data integrity and possible duplication etc.
thanks for the in-depth explanation, does a OneToOneField not require a join?
it does
a OneToOneField is just a unique ForeignKey
yeah, so in terms of performance, why wouldn't you just have one table for everything then?
for the above reasons
I'd say it depends on whether all the columns apply to all possible rows (in this case, each user has a profile)
so if there are columns which don't apply to a lot of possible rows, what would you opt for? A foreignkey?
or a OneToOneField
depending on the case
for example.
say you have admin users and normal users
and only normal users have profiles
one user has one profile, and one profile belongs to one user -> OneToOneField
on the other hand, let's say that each user has a Country
one user has one country, but one country can belong to multiple users -> ForeignKey
gotcha, thanks for the awesome explanation!
yw!
how do i map my json mappping with the data of models and keep the same structure? https://gist.github.com/SkyBulk/52ccdab577c94bde399c3b6ae8288208
guys I'm getting an error which I don't know how to fix. I visited my IDE today and tried to
python manage.py runserver but it said Python was not installed (neither was Django), so I reinstalled both... Now I get this error:
https://pastebin.com/i8abvSv5
In the body it says that
ModuleNotFoundError: No module named 'rest_framework'
So I'm really confused, I have done pip3 install djangorestframework and the same error occurs...
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.
seems like its a virtualenv problem
@native tide all i see in the errors are rest_framework not found in your python3.9, it doesn't show in any virtualenv folder
what do you get when you try to run echo $VIRTUAL_ENV in your terminal? it should show the virtualenv location
run that command in the folder with your pipfile
maybe type pip3 to see which python version pip3 running just in case
if djangorestframework exists in your pipfile and if it showing python3.9 for pip3. Check your django setting INSTALLED_APPS if you missing ,
for example:
INSTALLED_APP = [
'rest_framework' #<- Need ,
'django.contrib.contenttypes',
]
I can't find the pipfile
it's called Pipfile.lock right?
my settings.py has commas
it's 2am for me, I'm gonna go to sleep and just git clone my project (I think I .gitignored venv) and I will just remake my venv and reinstall Python. It'll work then, it worked before
oh right you just installed with pip install instead of a pipfile
I am working on a flask project. With stripe payment api integration. Shall I describe about my project in this channel?
hello, please do someone know how to make a custom filter in django-admin ? i don't find any doc (i am not talking about list_filter) but a custom filter like who took in input 2 values, and returns a dataset where the data satisfy a condition (maybe a data where the value is between the 2 values of the input)! thank you so much for your answers
if you want to filter by 2 dates range i suggest using this package as it's more supported https://github.com/silentsokolov/django-admin-rangefilter
else if you want to filter integer field you can use this package https://github.com/lukasvinclav/django-admin-numeric-filter
yes integer filters
like for price between X and Y
i already found the rangefilter for date
oh i will look on it then! thank you so much
Hi, I'm currently trying to import some modules on a Flask server and can't import them even when they are listed on my requirements.txt file
what error do you get when trying to import them?
No module named 'passlib'
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.
are you using python3?
you installed it with pip3 installed right? not pip install
ok
it's just import problem
currently running it with the code runner inside vsCode
runs it on the venv
but it run's properly with the python3 run.py
did not try that
so it work with python3?
yeah because you installed the package to python3.8
python3 and pip3 refer to your python3
python and pip refer to python2
@rustic yoke yeah it run on your selected interpreter python version
@gaunt marlin venv should always be on the root of the source code?
i'm not used to venv so i can't tell
i mostly use pipenv or poetry for my virtual package manager
there a fews but it's your preference which one you want to use
Should i use bootstrap or is it cool to use my own elements with css? With react
bootstrap is good for people who are not expert with css. I don't know other company but mine prefer to not use it if we already a frontend expert
Good, cause well that was gonna be a lot of work... lmao. I built all the static pages in html/css. Now implementing it into react/redux/Rest/Django. Fun times.... lmao not
Every tutorial ive seen shows bootstrap is why im asking
yeah for backend web dev like me, i have little knowledge on the front end so boostrap is a life saver on some tasks
I learned to do both sides long time ago. But that was html/css/js/ajax/php back in those days. This new fangled stuff is a headache
Anyone good with php i need help 😩 😫
Post your problem here man
kinda weird to ask PHP question on a python server XD
Hey @civic kiln!
It looks like you tried to attach file type(s) that we do not allow (.php). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .webm, .webp, .flac, .afdesign, .m4a, .csv.
Feel free to ask in #community-meta if you think this is a mistake.
im trying to create a login form where users and admin can login but when i press log in im not redirected to another page but im just staying the login page
i can send my code
But looks like ill have to dm the code
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.
I am still out of logic in this scenario: I have a big json file, I want to show data from that file in a webpage and apply pagination. How can I do that in django?
@civic kiln why you not using <form> for login?
how can you send data to the backend?
here an example https://www.w3schools.com/howto/howto_css_login_form.asp
We aren't allowed to use css, js and bootstrap its denied in my assignment brief
<form> belong to html, not css,js and bootstrap
How do i program web_host by myself in python?please send a tutorial or a guild.
hello everyone, i just finished doing my admin panel (that works correctly with all the customization i wanted to have) but i would like to add some unit tests, but since i never did this, can someone give me an example where the unit tests are useful for the admin panel for example ? thank you so much (i know what is a unit test, and how to write it, but i don't see what to test exactly since there is no "back" or "front" separated like i did in my first web projects)
Hello,
- Im here running python3 src/api.py
- src
- fonts
- bla-bla
- templates
- main.html
- api.py```
I got the following structure.
Im trying to display text on my website with the font `bla-bla`. in `api.py`, `main.html` is being rendered inside
```py
@app.route("/")
async def home():
return await render_template("main.html")```
In `main.html` I access the font like this:
```css
@font-face {
font-family: bla-bla;
src: url('src/fonts/bla-bla');
font-weight: bold;
}```
But it somehow the text on the page isn't being displayed with that font
I have a django database which consists in this:
class Image(models.Model):
url = models.CharField(max_length=200)
description = models.TextField(default=' ')
I want to pass both things to a view i want the image to be random and i want to put the url in the image tag in the html
I want to do this:
<img src="{{image}}" alt="">
but the image doesn't load
the code of the view:
def home(request):
ls = [i for i in Image.objects.all()]
r = random.randint(0,len(ls)-1)
context = {
'image' :f"<img src = {ls[r].url}>",
'description' : ls[r].description
}
I am working on a flask project. With stripe payment api integration. I successfully create payment system for fixed price product but I need more advance option.
We basically build a payment system in our web app. We are using FLASK for the backend. Generally main idea is when a user come to our site and choose a product and then they will pay us through their stripe account. We need to fetch the amount for that particular product from our business stripe account. When the click "subscribe" or "pay" button they will automatically redirect in stripe billing fork and see the amount of that product what they selected. Then they just enter their card number and click pay. Wala! hugging. They paid me for my product
This is the idea for fixed price.
Next idea is if client select products and if that product is fixed price like he want to buy a watch then it's not so complicated because you just call the stripe api and pass the product data through it. But suppose you select a plan like an email service that allows you send a email to thousands of your customers at a time. In that case, you need to count the amount how much email they have sent and bill them monthly basis for those particular emails. Unlike you bill your clients $20 or $70 every month.
how much they use our services they only need to pay for those. Let's say Client A use 20MB in this month so he need to pay $20 for this ($1 for 1MB). But in the next month Client A use 50MB so he need to pay $50. Rather than billing him $20 every month or only give him fix storage like 100MB, after he use 100MB he will not able to use any data anymore. For example a prepaid card or metered billing
My question is I successfully test the fixed price system. But I don't know how to test this metered billing. Have a look in the screen shot. It is for fixed price.
Here is my github repo. But didn't pull the code for metered billing. For now I just code for fixed price. I tested meted billing in my local machine.
And stripe docs for metered billing that might help you
It's the same thing, if you have products depending on the number of products is how much you charge, it's up to you to track the email usage going out of your system and make the calculations to then charge them every month and send that statement through stripe @violet zealot
How do i program web_host by myself in python?please send a tutorial or a guild.
Can you?
What's the difference between unit parameter and quantity parameter? In create function they pass unit parameter and in usage record parameters they pass quantity parameter. First I think that unit parameter is that what they count is the usage record then when I see quantity parameter I really get confused about unit parameter and quantity parameter. @haughty turtle
Hello is django or flask good for a web app or should i learn to work with a js framework ?
oh thanks i don't really like js so i think i'll try django
Same error
help(: ```
AttributeError :'str' object has no attribute 'get'
i want to make a reply post but when i go to sumbit the reply this erorr appears
Hello, I am just trying to solve a problem to map the data where it needs to be using a serializer. I Know a serializer, but how do I map the JSON data structure with the PostgreSQL data to keep the same ordering header, technique_id, subtechnique_id? https://gist.github.com/SkyBulk/52ccdab577c94bde399c3b6ae8288208
@noble smelt print(request.data) to see if your frontend is sending anything to that view
hello everyone, i am having a little problem, django-admin does no longer generate the id (primary key)
if i don't put it in my models, nothing works 😩! and when i try to add :
""" id = models.AutoField(primary_key=True) """ it doesn't work
@dawn heath so, to confirm, do you want to serialize JSON into python, or deserialize (python -> JSON)
@livid coral so primary keys are not auto-added to your models? What is the error when you try to do it yourself with the AutoField
U mean request.GET? It's empty
with the autofield, it just saves the data in my db without an id, and in my admin panel i got this answer :
even if it stored in my db (without an id, but only with the _id generated by mongodb)
@noble smelt well, check request.data
And for that you need a POST request, you're using a GET request
@livid coral did you migrate then makemigrations?
@native tide the last one who you dont answer him its me(:
@noble smelt when you make a GET request, your parameters are not in the requests body. They're in the URL.
But you can access them with request.GET[key] so somethings not right on the frontend.
Try use axios for your request library. It's much simpler to understand and less lines of code.
Also is_ajax is deprecated
@mystic wyvern because you provided 0 information
yes
i deleted all the pycache, then deleted the db, i created a new one, migrate all the project, and whenever i create a new instance it don't do the primarykey generation, they want me to created manualy
i can code a function that do it but i would like to understand what happened and why django doesn't generate it
Strange
knowing that in that project it was working correctly before, but i changed the models (that's why i deleted all the cache and the db so i have a new models in my migrations)
can i ask you please about another issue i am having?
go ahead
@dawn heath so, to confirm, do you want to serialize JSON into python, or deserialize (python -> JSON)
@native tide the other way round actually
i deleted all the pycache, then deleted the db, i created a new one, migrate all the project, and whenever i create a new instance it don't do the primarykey generation, they want me to created manualy
@livid coral this happens to all models?
even new ones?
oh thanks i don't really like js so i think i'll try django
@warped harbor you’ll need JS to make your site responsive anyway
You are probably using some_string.get('some_key') instead of some_dictionary.get('some_key').
Why don't you copy and paste the line in your script file that this error is pointing you to?
@vestal hound I disagree that it's the other way around, DRF's Serializer takes a JS object from the request and serializes it into python, no?
by "JS object" you mean "JSON"?
I will go with serializer way , how can I write the serializer to achieve the following? I am just trying to solve a problem to map the data where it needs to be using a serializer. I Know a serializer, but how do I map the JSON data structure with the PostgreSQL data to keep the same ordering header, technique_id, subtechnique_id? https://gist.github.com/SkyBulk/52ccdab577c94bde399c3b6ae8288208
that's deserialisation: the conversion of raw data into complex types.
https://www.django-rest-framework.org/api-guide/serializers/#serializing-objects comment -> JSON is serialisation
Django, API, REST, Serializers
it's not different for DRF.
how can I do ? I mean imagine I deserialize or serialize ? how can I push all data belong to?
in general, serialised data is what you can send over a connection because it has been reduced to a simple representation
Django, API, REST, Serializers
good place to start
basically a serialiser is a class that turns a model instance into some more primitive format (e.g. JSON string), or vice versa
note that DRF's serialisers perform both serialisation and deserialisation.
i have my serializer as my model, but i am not getting a good way to properly match where each tactic, technique , subtechnique match to belong to
I do not see any serialisers in your code
@vestal hound oh, yeah, I see. I've been "deserializing" all this time when I thought I was serializing
this is my code for serializer
from rest_framework import serializers
from apps.api.models import Tactic, Technique, Subtechnique
class AttackSerializer(serializers.ModelSerializer):
class Meta:
model = `??`
fields = '__all__'
I dont which model to add to
a ModelSerializer must have an associated model
or serialize all models one by one
yes, I know , but which one? all
one serializer per all data stored?
I want to perform AttackSerializer(serializer) as my wrapper of all , and keep the rest as class TacticSerializer(serializers.ModelSerializer): etc
how do I add a favicon using python
I have this but I am trying to add a favicon
import os
import random
from flask_discord import DiscordOAuth2Session, requires_authorization, Unauthorized
from threading import Thread
from requests_oauthlib import OAuth2Session
app = Flask('')
@app.route('/')
def home():
return 'Fireball Bot is Online!'
@app.route("/about")
def about():
return "<h1 style='color: red;'>I'm a red H1 heading!</h1>"
@app.route("/admin")
def admin():
return redirect(url_for("home"))
@app.route("/invite")
def invite():
return redirect("httXXXXXXXXXXXXXons=8")
def run():
app.run(
host='0.0.0.0',
port=8080
)
def keep_alive():
t = Thread(target=run)
t.start()```
ping me when you respond
ok I decided I would just use html but here is my home app.route @app.route('/') def home(): return render_template('web/index.html') and here is my directory stuff
but I am getting this error
jinja2.exceptions.TemplateNotFound: web/index.html``` is there something I have to do to make it a template
your static path probably wrong
what do you mean and how do I check that
the flask docs kinda hard to go through i'm just gonna give you the answer https://stackoverflow.com/a/48040453/11225821
you need to set template_folder path first
ok do I still do web/index.html or take the web/ out
ok I had written this html code before but why does on one hoster it looks like this
and on another
it looks like this
@gaunt marlin
check your css path
are you copying from some website?
css are needed for styling
maybe it's in styles folder
Can I create a open web-access URL with python?
like just using ip-address instead of a domain name... I guess I do have domain names I could use.
I would guess I would need to use an NGINX or apache web-server
What I want to do is create a one time use web-page, log time-zone and user-agent of user, and trash it.
For a time-zone discord bot
i think that related to more how you config the load balancer
Open-source & free to use video player, button, textbox, textarea, website designs and templates for web developers and designers. | DW Assistance
check out if you are a beginner web developer
kinda hesitance to click random link on the internet :/
i need a little help here.I am working on Django food ordering system with a Ml model.To make it work i want retrieve the field value from the database which i am unable to.I once did but its type is Query i want it to be int. Basically i want to store the field value into a variable(type int) in Django and pass it in a function
A help will be appreciated
Guys why web development is famous I cannot find any web ideas???
Hey everyone - I’m getting ready to start my first django project and was looking for some guidance. The main app of the website is going to allow users to specify several parameters that will then be consumed on a schedule to run a job. What is the best way to do this? Does django have some sort of multi threaded processing queue built in? ...Should I be looking into async? Want to make sure the server doesn’t get locked up when it’s running these jobs and users can still access different parts of the website. Thanks in advance!
hello, i have a question for someone who has experiences on domains. So i have a little website and i don't have an SSL certificate yet. When i invite people to my website, they seem not to stay longer than 10 seconds. I'm guessing the reason for that is the SSL Certificate. I'm planning to buy it soon. In my provider, i'm given 3 options for SSL certificate. One is called Standard SSL (attributes: domain ownership validation) also the cheapest one. And other 2 are basically double the first one's price and their attributes are similar which are ownership validation, lock icon in the browser. my question is, which one should i buy in order to make sure that people won't think my website is a scam?
low key wouldnt both buying a ssl cert and use cloudflare with strict cert
I have the required message. When I open the page it shows but when I submit it disappears. Why?
yes
well i am reposting it here since i am stucked in it for too long
the auto increment that is included in django isn't working and i don't know what's happening, i installed django-admin and set up an admin panel, my db is in mongodb..
my class in models is :
class Tag(models.Model):
tag_name = models.CharField(max_length=100)
def __str__(self):
return self.tag_name
class Meta:
ordering = (["tag_name"])
db_table = "Tag"
in my admin.py :
@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
list_display = (['id', 'tag_name'])
list_display_links = ('tag_name',)
search_fields = ("tag_name", )
class Meta :
model = Tag
HI all,
how do I handle PubSub subscriptions? If I subscribe to a topic I get the seconds till the subscriptions end. Should I save this and generate a Cronjob with resubscribes if the leasing ends or should i just refresh it every day by a cronjob?
!developersverify
hello, I have a huge json with a lot of data that I would like to transform into a website. What could be the best way to do it?
json to database and from there a Flask?
I dont have any experience in web dev with Python
if easier, I also have the data in CSV format
CSV is 10000000000% easier
because you can use pandas to directly read and process it without nuking your RAM
ok thanks! and with csv i port it to a database and from there I create a flask that outputs that db?
would be the easiest yeah
awesome thanks, will try to dig deeper from there
Hey all, I'm looking for someone to talk to for a few, if someone's available, about frontend vs backend for authentication implementations. It's been a while since I've done this. Trying to understand the workflow for backend (like, I don't know, there's just a missing piece in my head)
im trying to do the login form for multiple roles but im getting an error
can someone help me out
thanks in advance!
how do I Map the json into my serializer to map the data where it needs to be? https://gist.github.com/SkyBulk/52ccdab577c94bde399c3b6ae8288208#file-serializers-py
Hello, the CSRF option for django, is it only applicable for HTTPS?
I'm new and was just wondering if this server has any experience with Django?
ok... i dont understand whats going on... i added ```py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
when it saves the the db it links to the right spot, but the image wont open. before adding the media root i could view the image in react.js but it says the link `http://127.0.0.1:8000/media` doesnt exist
and yes, its uploading the image to that spot fine
it's in the channel description
just ask.
sorry, I'm still kinda new to discord. I'll check those descriptions from now on
so what's your question
or do you not need help right now
btw it's not a problem, just a reminder
welcome!
I posted my full question in the help-argon chat
I'm having trouble sorting models with ForeignKey
well alright, upload and display works now. i feel like im getting somewhere in this program now... although this project is a serious task doing all the work by myself from the ground up.
Am i just dumb? How do i sort my queryset in rest api with django?
in your view?
is possible to add functions as utility in serializer.py django?
Eh i figured it out. I did
class ViewSet(viewsets.ModelViewSet):
queryset= objects.all()
filter_backends = [filters.OrderingFilter]
ordering_fields = ['id', 'datetime']
ordering = ['-datetime']
could someone help me integrate a boostrap in django?
What do you mean? @acoustic oyster
i dont know as much about sql as i thought... or maybe its just django, but how do i make the uid of the post = to the id of the Users table and get the username. i know its with foreign key
In Flask, I found some resource that says I can use bootstrap with a plugin called flask-bootstrap. If I use bootstrap cdn in my <head> section with <link..... >, that's also work fine. What's the difference between them? And what is the best practice for a developer?
Theres not just flask-bootstrap (Bootstrap 3), but also bootstrap-flask (Bootstrap 4) flask-bs4 (bootstrap 4) and probably some more.
Generally, there is no best practice in this case. Would you rather have a additional dependency, or manage all bootstrap formatting yourself?
The difference is that these flask extensions give you pre-made templates and other things meant to make using bootstrap easier.
hmm. I think using bootstrap in <head> section is more easier rather than using a lot of plugin
hello where can i host my flask projects or do i really have to use like aws lambda for serverless functions
@vivid spear you should host your website on a VPS, any VPS is ok aws is just one of those services
Can someone please tell me a cheap way to host a Flask project temporarily?
@lament nebula you can use heroku hosting, it has free option
there plenty of deal on other hosting sites that go for very cheap
Thanks, but I have already used up my Heroku slots. I need to host this project for a week. Is there a cheaper solution?
I was looking at Hostinger, but I couldn't find any documentation for hosting projects/frameworks... 😶
just get like a 2$ vps for a month
From where?
I face some problem when I am practicing flask framework.
when update something in my code, like color or content in my preview (in browser) my content isn't updated. It was still the old one. Why I'm seeing this problem? But when I close my browser and restart the server then my content is updated. Any thoughts any this problem?
boys
coming from python i used pycharm and now i am getting into js
jetbrains have webstorm as an ide for js
are there any limitations compared to vs code
that will probably be down to your browser caching the response of the server, best method i would say is either set cache rules (if you can) or use incognito to view changes
Webstorm is incredibly powerful, much more powerful than VSC without a considerable amount of plugins and sometimes still more limited
the limitation is that webstorm is still as beefy as any other JB IDE and naturally carries the weight of it
I tried incognito mode and hard refresh. When I do heard refreshing my css code is updating but my html code doesn't updated. @quick cargo
Hi Everybody, I am a N-Tier developer for more than 10 years, now I would like to go with microservice architecture but I dont know where to start. Do you have any recommendations, tutorials or articles?
how do I Map the json into my serializer to map the data where it needs to be? https://gist.github.com/SkyBulk/52ccdab577c94bde399c3b6ae8288208#file-serializers-py
I have a flask app with sqlite as database and sqlalchemy as ORM, hosted on heroku.
During development I created an account for testing and then pushed the code with database to Heroku. When hosted I again created some other accounts and after some bug fixes I pushed code from GitHub again and then found that account data of all accounts that was created during the website live has been deleted and again only one account is there , that is the testing account.
It means every time I updated the database got replaced by one on my GitHub.
Why is it happening ?
And is there any way of preventing it.
App link : http://nazninapp.herokuapp.com
My flask run code
if name == 'main' :
db.createall()
app.run()
Hope i could post this here ?
@quick cargo Problem solved. Just use set FLASK_ENV=development instead of using set FLASK_DEBUG=1. Really it's perfectly working
can someone help me out here plz
hey guys , django question, to_representation or overwirte list method?
How do I download Django?
pip
I tried doing that through the windows command prompt but it kept saying that it didn’t recognize pip
Oh ok thx
If you don't have pip, you would need to install pip before Django.
Django Question (or even general webdev): Anyone know of a good tool for analyzing for why a view might be loading slow (it's making a few external api requests before rendering but i'd like to target the longest requests first)
Can you make web games using python
that are also multiplayer
like an fps or something
or is python too slow
How do you install pip?
how do I save an array in this model without loop? sector, tactics, techniques, subtechniques = UpdateAttackMapping().populate()
class Tactic(models.Model):
tactic_name = models.CharField(max_length=100)
the model contains an array?
or save an iterable of models?
yes there are some services such as pythonanywhere or heroku
k\
cause python is my main lang
but idk if i should make sites in it or no
do you recommend @gaunt marlin
kinda hard to ask me to know if you want to make a site or not, it's your decision
should i use django or flask
django if you want a built in admin page and other functions, flask if you want to customize everything
i dont understand what you mean
you should learn about web development first then
web development is broad, flask and django are just framework to create the backend side of website
you use what framework you needed for each situation
yes
and i would not use it for front end
ok, thanks for explaining
youd use something like react.js or angular for front end. theres also a few others out there
react is also pushing to the backend these days. as well to make it not so resource dependent front end
Is it possible to embed tkinter into a web browser?
Basically, I've build a socket server in python that communicates with a client that runs tkinter. Don't ask why, but now I need to create a http client. Since http can't communicate with tcp (for obvious reasons), I have 3 options: Rebuild the tcp server as a web server, build a proxy, or embed the tkinter (if possible). Since I really don't want to rebuild the entire server, and I also don't have much time, I want to scapegoat my way out by embedding tkinter if that's possible.
ok, I think I am going to need to build a proxy -_-
it is???
yea, read an article on it today... its called rcf if i remember right... allows you to build component on the server and push in pieces decreases the load time of massive pages or something like that. im a noob with react i didnt fully understand everything i read
are you talking about server side rendering?
yea that was mentioned in there. it said something about you can already do it with workarounds, but its becoming built in. or something along those lines. ill see if i can find the article again if you want
based on your description
that sounds like SSR which, to my knowledge, is not currently built into React
yea, SSR is was also mentioned. it was an article that popped up on my google discover so i read it. dont remember all the details because at the time didnt seem super inportant
@wicked elbow, no
yes, seriously though. SSR is already a thing though. and using a node server, you can send static html rendered on the the server and display on the browser. thats ReactDomServer. Its possible the article i read was older too because i see a ton of posts mentioning react SSR. like i said i didnt soak to much of the article up though as im still fairly new to client side frameworks. im used to building static pages or using php to giving the static page.
grr... why is the django server so slow loading the stylesheets. refreshed the page, cleared the cache and the classes still arent showing...
.buttonVisible {
background: #F0F3F4;
border: thin solid #3a4660;
transition: border 1s ease, background 1s ease;
}
.buttonHidden {
background: #FFFFFF;
border: thin solid #FFFFFF;
transition: border 1s ease, background 1s ease;
}
``` these arent doing anything, class changes on the element, but doesnt render. it worked before i switched to it class instead of jsx. maybe its an id style, but doesnt show marked out on chrome so idk anymore lmao
web development is boring
yes django is very broad, it will take a long time to understand it all
i am, what are you having problem with?
So I want to make an OAuth v2 framework for my already-made Django app. Do you have any resources specifically for that
yes there are 2 popular packages for oauth v2 that being used now is django_social_auth https://python-social-auth.readthedocs.io/en/latest/configuration/django.html?highlight=django or django allauth https://django-allauth.readthedocs.io/en/latest/installation.html
i like allauth more because it support more services/providers
Sweet! Thank you so much!!
i just edited it, the allauth link was wrong so i fixed it
oh ok dope
these alot of tutorial on youtube with allauth for example https://www.youtube.com/watch?v=qqFCt0Yde40&ab_channel=JustDjango
This is the first episode of the Django Package Review series. In this video, I talk about Django Allauth - probably the most well-known package for handling login, registration and social authentication in Django.
https://learn.justdjango.com
☝ Get exclusive courses & become a better Django developer
Follow the code here:
https://github.com/j...
Sweet! Thank you!
https://stackoverflow.com/questions/65518964/django-prevent-models-from-updating-based-on-conditions
can someone please help me here?
thanks!
anyone know why this is giving me an auth error?
const config = {
headers : {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': `Token ${token}`
}
};
axios
.post('/api/web/', form_data, config)
you can use django signal pre_save to check before saving object https://docs.djangoproject.com/en/3.1/ref/signals/#pre-save
please post the api view, we can't find what wrong from the frontend call, maybe check if the token is correct by calling api from postman
everything worked correctly until i added authorization into the mix... but hold on
I meant update
yes pre_save is also applied on calling update() or save()
class PostsViewSet(viewsets.ModelViewSet):
queryset = Posts.objects.all()
permission_classes = [
permissions.IsAuthenticated
]
serializer_class = PostsSerializer
filter_backends = [filters.OrderingFilter]
ordering_fields = ['datetime']
ordering = ['-datetime']
def post(self, request, *args, **kwargs):
src = request.data['src']
uid = request.data['uid']
Posts.object.create(src=src, uid=uid)
return HttpResponse({'message': 'Image created'}, status=200)
``` thats the api view
how do I check if its the update method which send the signal
@twilit needle before you doing update with save() add update_fields argument to the save() call
a = YourModel.objects.get(pk=1)
a.field_name = 2
a.save(update_fields=['field_name'])
I am working with drf
Have a view like this
class RoleRetrieveUpdateDestroyView(generics.RetrieveUpdateDestroyAPIView):
"""
An API view to create, retrieve or destroy roles.
Doesn't take in the role's position as a parameter, though.
"""
# make sure that default roles' names as well as colour cannot be changed.
queryset = api_models.Role.objects.all()
serializer_class = api_serializers.RoleSerializer
permission_classes = [IsAuthenticated, ManageRoles]
class Role(models.Model):
class Meta:
ordering = ['position', 'cluster']
required_db_features = {
'supports_deferrable_unique_constraints',
}
constraints = [
models.UniqueConstraint(
fields=['position', 'cluster'],
name='deferrable_unique_role_position',
deferrable=models.Deferrable.DEFERRED
),
models.UniqueConstraint(
fields=['id', 'cluster'],
name='relatively_unique_role_id'
)
]
# cluster and id must both be primary key
# to make sure the endpoints make sense
objects = api_managers.RolesManager()
id = models.BigAutoField(primary_key=True, db_index=True, editable=False, auto_created=True)
permissions = BitField(flags=permission_flags, default=default_perm_flags, db_index=True)
position = models.PositiveSmallIntegerField(null=True, blank=True, db_index=True, editable=True)
name = models.CharField(max_length=100, validators=[MinLengthValidator(2)], db_index=True, default='new role')
color = ColorField(db_index=True, default='#969696')
cluster = models.ForeignKey('api_backend.DataSheetsCluster', on_delete=models.CASCADE, editable=False)
created_at = models.DateTimeField(auto_now=True, editable=False, db_index=True)
REQUIRED_FIELDS = [name, cluster]
and a model like this
what I want to make sure is during the update method of the drf view,
I dont want the name or color of the role object whose position is NULL to be updated
alone
no the fields differs for different objects, like I mentioned
@twilit needle you can trigger by writing it in bulk_create() method of manager https://stackoverflow.com/questions/30632743/how-can-i-use-signals-in-django-bulk-create
@gaunt marlin yea, so all i had to do was switch the spots of the headers... the 'Authorization' header had to go first, then the content-type.... literally makes zero sense, but hey. it is what it is
during model updation is this called?
ehm i don't know axios so i can't tell
next question though if i set the user-id of the post as a ForeignKey(User) will that let me pull username from the database... i dont understand the models of django very well
on single update you can trigger by using save() with update_fields argument, on bulk update you can use the one answer i paste above
okay so I am doing single update only
Can I override the model's save method instead
to update
sure
both signal and save() work the same, pre_save just trigger before save()
if you want to update foreignkey field by id you can set fieldname_id=id
so you dont need to call instance of the object
alright, so im saving posts with uid=some# but it needs to linked to the username of whatever USER id=? that way if a username is changed down the road, the uid is still the same, but it changes the username on the post if you understand what im saying... is foreignkeys not how you do that?
i don't quite understand what you are saying, you want to change username with user has uid = something ?
ok so when a person posts, the post will be tagged with their id# passed through state, i need the way to return the username from that id... i suppose i could just querry the user table where id = uid and only return the username, but that still seems dangerous...
you using JWT right? you can get user instance from that jwt token, so the user that call the api can only get their username
if you print request.user in the view you can see which user instance calling
so say 100 people post on the a forum. each post is tagged with their uid not their username, because usernames change, but user ids dont... if you saved to an old username it wouldnt update to the new username... i need to link the usersnames to the ids on the posts
ah ok
hmmm
i still wondering
why you not just set user_uid to the post id?
you querying user right?
shouldn't be anyharm
if you just want username from the query use values_list('username'), it only return username from the query(no other info)
yea, but doesnt that take up database resources.... if a 100 unique ids are on posts, id have to querry for each. how do you set up a serializer that accepts 100 ids to return in one output.
again why i assumed a link between databases would be better, but again, im not that knowledgeable about django models/serializers
@wicked elbow actually the user would have manytomany link to a post
so you only need to query for the post id
and return uid, username of manytomany field in a list
it's easier
okay, but how is it setup? for the models and view?
model post has manytomany to users table, in the view you can have custom serializer method that return all username as a list from querrying post.users.all()
the model would look like user = models.ForeignKey(User, on_delete=models.CASCADE) right? linking user to Users. then in the serializer, i pull username from parent?
ya, i set it up.... the User model has a get_username() method so i can querry for only username. itll also give my trackbacks to posts by user, which will be good for a profile view, querry for all posts by username ect
why is this import not working? Import "users.schema" could not be resolved
@native tide Are u still here?
its because you are already in schema
importing would make no sense at all
can anyone help me at #help-corn
Hello I've a question regarding Flask
Let's say I'm taking requests to an endpoint /node_web
I want to catch all sub-requests like GET /node_web/example in the same function, how do I setup that?
Mention me if anyone is answering please.
hi
is there a way when using CreateView to save the data from the form only when a certain condition is met?
Hello dear comrades, i need help with cookies
for some reason, this line
resp = Flask.make_response(render_template('login.html'))
causes this
TypeError: make_response() missing 1 required positional argument: 'rv'
am i doing anything wrong?
resp = Flask.make_response(render_template('login.html')) newCookie = generateUUID() resp.set_cookie('uuid', newCookie, expires=(datetime.utcnow() + timedelta(days=7)))
It depends
Is there any repository with DRF messages (django.po) already translated for some languages?
Nice
@cerulean remnant Thanks, appreciate that.
can i show off my project here?
I wouldn't mind 🙂
I have experience with python but not with web development. I was trying to get some insights on resources and frameworks I should aim for as a starter
what does rest_framework.authentication.SessionAuthentication do exactly? do I need it If I am using JWT authentication? I currently have it on because from what I understand it is needed for CSRF. Is that all it does? are there any security issues/ implications of having it on only for CSRF? if I should disable it, what would I use for CSRF?
my current project. react.js/redux/Rest Api/Django. need to learn the models and querysets better if anyone wants to explain them. im literally lost. i know basics of databases, but not linking tables
I am looking for the best django free course which is for beginners. I have done python fundamental tutorials and now looking to get into web dev. Plz help me suggest a good django tuturials or course for beginners
I have experience with python but not with web development. I was trying to get some insights on resources and frameworks I should aim for as a starter
just depends honestly... id suggest react. react.js is web side, react native is mobile. but its really whatever you want to learn. theres also angular thats used a ton. as well as others. its not a simple answer. way to many choices and growing all the time.
now how in the world is django allowing me to add to the database with an empty value with blank=False?
blank=False is for formfields
but unless you have null=False as well, you're still allowed to add null values
ah that makes sense. duh. i mean when you create a table its literally NOT NULL lmao
Hello everyone. My name is Michael. I've spent the past 12 years or so bouncing between different trades (military, Chinese translator, business major, English teacher in China). Saved up enough money to study webdev for a year with the goal of becoming employable by the end. Studied a bit of C# over the past few months, and ultimately decided to focus on HTML, CSS, and JS before going any further into other programming languages. My main reason for joining the discord channel is to find a mentor that would be willing to offer some level of direction and clarity over the course of this year. Between family and general life stuff, I have 6-7 hours/day allocated for study and practice purposes. Front-end seems more up my alley for the time being given my goals. Any advice is greatly appreciated and I hope to find more likeminded people here (and hopefully a mid-long term tutor). Thanks for reading this block of text!
Apologies if this is the wrong place to post this
Do gunicorn and other wgsi-compatible web servers invoke the application callable (or other specified callable) upon each refresh? Assuming that is what happens, does a framework like Django then handle that request with all of the given information and send a response back?
Has anyone else had a problem with CSS not updating while using Flask Framework in Python? If so, how can I fix this.?
its not just flask... the server is stating the css hasnt been updated and sends a 304 redirect to the cached version. saves on downloads of the same file. sometimes its a little slow
def get_queryset(self):
queryset = Posts.objects.all()
feed = self.request.query_params.get('feed', None)
if feed is not None:
queryset = queryset.filter(type=feed)
return queryset
this isnt filtering for whatever reason heres my axios get
// GET FEED
export const getFeed = () => (dispatch, getState) => {
axios
.get('/api/web/?feed=true', tokenConfig(getState))
.then(res => {
dispatch({
type: GET_FEED,
payload: res.data
});
}).catch(err => dispatch(returnErrors(err.response.data, err.response.status)));
};
``` anyone know why?
oh ok thanks
depends, what do you need? just ask here if i dont know the answer someone else might
so I am making a custom model field, that takes the value and decomposes it into binary for storing into a database. Upon retrieval, it reconverts the value from bytes.
I am having the field right now here
https://mystb.in/PublishedAllenFeature.python
but I think this can be better implemented. can someone please help me with this?
thats way over my head, sorry. i cant even get my filter to work passing query strings...
okay am waiting for someone who can
wooo i managed to get it to work with a different field
Can I ask simple express question here? Basically I make an API call and obtain user's ip. Although it's server's ip instead of the user's ip. I'm not sure if it's heroku, but how should I solve this? This is what I have axios.get("https://api64.ipify.org/?format=json") // Get User's IP Address.. Is this because it's in express (server)? Maybe I can make the call in front-end and send this data.
It's free. No API key needed btw
so I am making a custom model field, that takes the value and decomposes it into binary for storing into a database. Upon retrieval, it reconverts the value from bytes.
I am having the field right now here
https://mystb.in/PublishedAllenFeature.pythonbut I think this can be better implemented. can someone please help me with this?
@twilit needle better in what way?
hi if anyone has used a software called xampp before please let me know. Im confused on what to do if my files dont show up in a list
the django docs is very confusing, I don't even know if I am right
If I want to implement this idea, is this the only way to go?
I want high consistency and speed
Django is ridiculous when it comes to documentation.. rest api isnt much better...
guys need help... working on a web scraping code with selenium. the website blocks bot action but grants access to manuel input. what can i do?
alright... so react aint working for me... im using componentDidUpdate to requery to change whats showing on my page, but its not rerendering after requerying... shouldnt that be called on prop change
cant help you here.... we dont break sites ToS
this is the web dev comunity. most of us would agree, that if we were paying to run a server, and didnt want bot access, we would hope people didnt try to get around it... comes down to bandwidth and cpu usage... not every site is built for huge pulls of data off the site. even on big sites its normally bandwidth restricted/page refresh from ip restricted to keep people from comsuming all their bandwidth... on a small server it would be similar to a ddos attack.
I'm trying to fill a table of Select with data from my database, I saw on the internet I can do something like
form.field.data = newdata
but it's not working, It's throwing an Error
AttributeError: can't set attribute
My code is:
template_form['schedule'].TwoDTable.data = template_previousSchedule
Where
template_form = {'whosTable': whosTable_Form, 'schedule': scheduleTable_Form}
scheduleTable_Form = forms.scheduleTableForm(meta={'csrf' : False})
and
class lessonForm(Form):
Lesson = SelectField('', choices=args['Lessons'], render_kw={"Class": "lesson"})
class scheduleTableForm(FlaskForm):
TwoDTable = FieldList(FormField(lessonForm), min_entries=66, max_entries=66)
changed = HiddenField('changed')
submitToDB = SubmitField(label='submitToDB', render_kw={'value': 'עדכן'})
It seems like the setter is broken ?
I've looked at the procces functions but I don't get how to fil lthem
can someone please help me like give suggestions to implement the following idea?
https://stackoverflow.com/questions/65530636/django-efficient-ways-to-decompose-and-compose-user-data-to-and-from-bytes
thanks a lot!!
please ping me when help here or on stack overflow!
thanks for sparing your time!
I am using Quart websockets and I want to retrieve all connected clients and broadcast the message sent from one client to the rest
https://paste.pythondiscord.com/kabiwumoqe.py heres what I got so far
please ping with an answer and I will read it later on when im home again
We did a similar system design before we moved to a REST api for sending the messages and then only using WS for receiving message, but:
- We made a 'Room' class that essentially contains all the ws connections (any other info we needed to exist as a global state)
- the room had a
submitfunction essentially and then a global queue across clients with a waiter going through the events in the queue, (this avoids clients receiving events in different orders, this may or may not be important to you ig) - each client was a custom class with a event filter so it was easy for the actual endpoint to call events without being messy so all the endpoint did was
client(op_code=x, data=y)
What would be a good idea if you intent for this to be used for many clients and want to scale it to more than one instance, i would recommend using a message emiter and receiver system, something like redis or rabbitMQ so emitting on one process relays to the others aswell, but that'll depend on what you do
Hello guys I need your help regarding the deployment of my first Django app, heres how it looks when I type runserver(offline)
Good morning and happy new year. Can someone point me to the correct chan for a py3 json encoding issue ?
nm may have just answered myself
Could you recommend a course on Figma? That is rather oriented to the use of figma for design itself and web design.
@quick cargo I don't ever ask this but do you have any snippets I can check out. That are related to what you said
Hello everyone and happy new years! Hope everyone is having a great time and are healthy. Can someone tell me how much python should i know in order to learn django? Also, what are some good exercises for python beginners
@ornate shell Finish a course on Python and you should be good. I really liked Codecademy because they teach you Python then they guide you through some projects which you can do outside of the course.
Then you can focus on some libraries like django.
@native tide thanks!
Then if you're liking Django, you can look at other courses such as JS / React / SQL if you want to learn more about the web-dev ecosystem.
django or flask !?
which one is the best for building a website (dashboard) for a discord bot
(with a good access and manipulation of the databases)
neither
go with a asgi framework and server if you intent to run the two in the same process
if not then what ever but i personally would still go with asgi because easier to setup websockets for ipc
ok thankx
admittedly, Django supports ASGI now
(partially)
but yeah
Anyone here who can help me with a noob question?
just ask
How can I change the datatype of one element in a dictionary?
how do you identify the element?
and do you mean the key or the value?
The value beinig displayed.
city_weather = {
'city' : city.name,
'temperature' : r['main']['temp'],
'description' : r['weather'][0]['description'],
'icon' : r['weather'][0]['icon'],
}
In this case the temp value
do you want to change the type in place
or only after you access it?
do you know how to modify an element in a dict, in general?
I am not really familiar with changing one thing in a dictionary
do you know how to add elements to a dict?
(btw this is kind of off-topic for webdev; you can open a help channel #❓|how-to-get-help)
np, tag me there when you do
this question is kind of miscellaneous but ill ask it here. my site is both on www.site.com and just site.com. nginx manages that. the problem is it seems that browsers treat them as different sites. cookies, local storage, etc do not transfer between, it doesnt seem impossible to fix this in the frontend side, but its kind of messy. an idea i have at the moment is just make www.site.com redirect to site.com. github seems to do that. is this considered bad practice? are they any concerns or gotchas i should know about doing this?
not a clue, lots of sites have redirects though. including other domains for typos... www.google.co is redirected to www.google.com for instance
god i hate design... spent 20 minutes trying to get something to line up right. and then once its finished, it looks like poop... lmao
anyone know how to make a get querry when database requires an authorization token to access? to querry for username/email onChange for real time verification?