#web-development
2 messages Ā· Page 180 of 1
is django.contrib.staticfiles installed in your settings.py -> INSTALLED_APPS ?
Path looks correct so yeah check for the django.contrib.staticfiles
yep it is
I think you have to add a STATIC_ROOT that contains the path to your Static folder
The full django project path please
yeah i added that but still no luck unfortunately
Is the static in the app's folder?
no it isnt
Move it
no i have not, isnt that used during deployment?
how do I get the IP address of a request that I can request back some data?
Yes it is
done, still not working
can someone answer
like I can do requests.get(the_ip)
maybe in headers?
Is the full path djangoproject/app/static/app/image.jpg?
right this is why im so confused
yes
wait no it is not
I just recreated the same and worked fine for me
let's see if it works
@velvet yew my project and app are on the same "level" in the directory
š®
django.contrib.staticfiles will not serve static files when not in debug mode
Project and app are on the same directory ?
yes
That's how it should be
Not really, you should have project/project (setting.py etc.) and project/app1, project/app2 etc.
I'm rather confused at your directories let me double check
project/manage.py
it's not working
Anyone?
when I visit that IP it's loadin forever
Copy the full path to the image
C:\Users\Me\Desktop\alb2_rec\albumApp\static\albumApp
so on that IP I am hosting a web server
and I'm visiting another web server with that IP
when I type the IP i received in the browser (and with a correct PORT)
it takes too long to respond
I'm currently using an ubuntu VPS to dev my Django Application. There is no Apache installed, no Gunicorn or nothing. Just using the manage.py runserver ipserver. What is the best way for me to add a domain name to my django app ? Do I need a webserver (like apache or Gunicorn) ? Thanks !
domain names aren't made, they are typically bought
you should type your domain name into your browser to test if it exists
then buy it from the person selling it
note that this takes real money
you can also go to sites like godaddy.com do get a domain
or you can just use a free domain on launch to save money
I used DigitalOcean to create a django Droplet and a Postgresql database
and also yeah, you need to use nginx and gunicorn then bind an A record to your vps' IP and then accept traffic from that domain from nginx or apache wtv ur using, but I recommend nginx
Flask gives the warning to not use it's built-in server in production. If my (open-source) package spins up a server local to the user, is that considered production ? In other words, do I need to include tornado , aiohttp or something similar?
is there a way to pass the same variables through every render_template?
i have multiple pages that all rely on a variable that represents the current user session, and i have to pass it through every time
django.core.exceptions.ImproperlyConfigured: Field name user,status is not valid for model Post.
someone please help
Hi everyone, I am new to FastAPI and web development in general. I am looking for a reference code structure for my project. I want to create a website and looking for some references on how to structure a web project with FastAPI. Any links/suggestions ?
Hey, I reinstalled my project, I imported everything from the other server, but in HTML file I can't use {% block %} etc. I have set my template dir in project settings. Do you have a solution ?
If I create a new HTML file into templates, it works, if I copy it from my computer with scp, it doesn't work
Hello
How to make a file download?
Im making print(filebytes)
But nothing happens
This is not working
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.
Check the link, is almost the same as the stack overflow one
I use python CGI
And sys.stdout(file)
Not print
But it does not trigger the download file
Im using lighttpd
Ubuntu
And python 3
elaborate?
it would be useful if you still could give us the code snippet
There is not much many code. I just add headers, and then stdout the file readed
And nothing happens
I expected a file downloading
Maybe it's impossible
I call the cgi-bin from a ajax/jquery post
And i want in response the file
Yes
If i print text, the text is displayed in consile
F12 console
If i catch the response
So the program works, but not as intended
In 12h ill return and post it to you @native tide
Ty for helping
Now ill go and sleep, my brain hurts
taking breaks is very important otherwise you might burn out and completely give up
i might be off to sleep soon so dm me
if anything
Question. Anyone familiar with Django and class based views? I'm trying to use an UpdateView form to save to the DB. It works on a follow up Save, but not the first. I am only saving to the same object.
EDIT: I've got an idea...I either need to work with the form.instance properly or add a method to the model
My static files don't want to work at all. I don't know why, STATIC_URL is setup, STATICFILES_DIR is setup
Everytime I have "404 not found"
Traceback (most recent call last):
File "main.py", line 1, in <module>
from website import create_app
ImportError: cannot import name 'create_app' from 'website' (unknown location)
why am i getting that
trying to import from folder
@kind sluice
Flask gives the warning to not use it's built-in server in production. If my (open-source) package spins up a server local to the user, is that considered production ? In other words, do I need to include tornado , aiohttp or something similar?
Production in computer science means released to the public for some reason. Running a local server is fine just don't use it for an internet facing service.
Thanks. So for just providing a web user interface to an application running locally, Flaskās built-in server should be fine, right?
I believe so, as long as it's not public facing and just local
Hi guys
Thank you.
So...I've just finished the first major part of LanesFlow. This screenshot is of the dashboard for projects (PIPs - or Process Improvement Projects).
And I've pretty much completed the Project Management part of the app, along with the initial part of the dashboard. There is a fair bit of automation behind the scenes. Project rating for evaluating if a project should be taken on (and where projects can be compared to each other is now working). This screenshot shows three stages of the journey being described by the dashboard.
Project Selection Summary...shows projects with automated ratings based on 5 drop down field selections.
PIP Progress...shows the PIP in progress, what phase they're in. In this one, a target date for the end of the phase is missing, so the heading "Target Date" is highlighted red.
Completed PIPs...shows those PIPs that have been completed.
All in all this is very exciting and is looking and working better than I could have hoped. Lots of functionality behind the scenes to make this happen.
Feedback on initial impressions of the presentation layer welcomed. Being in a sole-developer bubble is tough. Looking forward to alpha testing.
Yes?
Good morning one and all..
Im going complete my MSC (cs ) with in few days, so i want start my career as a web developer. Any suggestions for what concept's should learn in front and backend in 2021.
Hey guys im developing an small api with Django for a test, but a got some issues with the data modeling. Can anybody helpeme?
Basically, the relations are ok, but when i make the queries on the service, the response that i got its not the users name(for a example), but its the Id.
here an img of my service:
and this one is my models:
and thats is the response of the check in and chack out endpopints
check_in
check_out:
can anybody help-me?
where are you even modeling a username here?
if the username is in another table and you're using the user id as a foreignkey, you need to use joins to combine the data
hold
here
usuario = is the username
and Check In usuario takes the nome of Usuario Table
usuario seems to be a foreign key. A one-to-one-field is likely just the refence to the other table. meaning it only contains the id of the user, and you need to resolve the correct record from the user table (no idea how exactly that works in django)
one way to get the username would be to do a join when querying the data, i'd suggest looking at how to achieve that in django. i'm not familiar with it
though it's probably specific to the rest framework you're using
the i know but im already clalling the ORM method to make the join and the join are working, the problem is that is coming the id of the field and not the name
it's probably an issue with your serializer then? not sure
if that's the case, are you sure you specifying the right column?
cause if the id is appearing, it probably means that's what you are referencing
well i only follow the documentation:
here a example: class CheckoutViews(viewsets.ModelViewSet):
queryset=CheckOut.objects.select_related('quarto').all()
serializer_class=CheckoutSerializado
quarto its the column of the related table
followed
can you link docs?
sure, hold a sec
can you link the specific one you used?
like the query
in the docs
too many
ok, in your checkinviews functions, does query set return a list?
i mean is queryset a list etc
if it is,
if you do something like this
for item in queryset:
item.usuario # this is your userobject,
item.usuario will represent an object for the user table or class in this case,
so you can just reference the username like item.usuario.username etc to get the username
if i understand what select_related does correctly
hmmm let see here if this works
select_related is purely an efficiency thing
it doesn't change the output of your query
??
what?
i don't understand what your statement is in relation to
i was just telling the guy how to get the related data he wants, as suggested in the docs
I'm clarifying that select_related is not needed to perform a join in Django
i see
it serves only to avoid the N+1 problem
how would you actually perform a join in django though?
in other words, if you're not getting the related objects that you were originally looking for, select_related wouldn't help
okay so this is something I found a bit hard to wrap my head around at first?
but
say you have two models: Country and Person, with the latter having a FK to the former
okay, backtrack a bit
the concept of "join" doesn't exist in the same way in Django
so it depends on what you want to get out of it
say the country has a gdp column and you want it to be present in each instance of Person
then you would do Person.objects.all().annotate(country_gdp=F('country__gdp'))
which I believe is similar to what the original question wanted
(two underscores mean "go through this table" in Django)
it's a simple case of linking related data in this case .. i.e primary key exits as a foreignkey on the other
isn't that the case here too?
like clearly if you want to perform a join, you must want some column from the related table
how are you relating the foreign key here? and checking if it's actually in the two tables?
it's not done explicitly
but
I mean
so on each instance of Person
there will be a country_gdp attribute
and that represents the value of the related Country's gdp attribute
i.e.
equivalent to
SELECT person.id, country.gdp FROM person LEFT JOIN country ON person.country_id = country.id
or something like that, I don't often write raw SQL
ok, and an inner join?
in this case they would be the same
what? left join and inner join will never return the same thing
left join shows everything on the left side and only filters the right
while inner join filters both
so, if you're saying what you showed me is a left join, surely there has to be some sort of different syntax for an inner join
that is literally untrueā¦
where every row in the left table has a match in the right table, they will return the same thing.
and that must be the case here because of the FK constraint
i.e. every Person has a Country
thatās what Iām saying
there is no way to perform an arbitrary join, AFAIK
you would need raw SQL for that
you said that performs a left join, i asked you about an inner join and said it would be the same thing?
it would produce the same result
which I think is a reasonable interpretation of āsame thingā
note that that was in the context of this
you're saying an inner join and a left join would produce the same thing?
yes?
bruh
because of this
i guess that would make sense in that case
ill try this
thanks for the help
Hello everyone, I created a Django Doplet in DigitalOcean, and I tried to create a domain name using 1&1. So I created my domain, I used a subdomain that I linked to DigitalOcean DNS. It worked well, but I don't want the site to be accessible anymore, so I deleted all existing links between DigitalOcean and 1&1, but the site is still available. Do you know why ?
And I deleted everything after
But the site is still available...
Is it linked to the TTL value ?
hey so i know this isnt a postgres server but
in django I do have to fill in the location of the database right?
if yes, how do I find out the location of my server from pgadmin4?
i cant seem to find it in the properties section of the database
Hey guys, anyone familiar with Cloudinary for django, i have a question
You can chain filters on the query for "AND" and you can use the Q operator for "OR"
Maybe you're still viewing the cached version?
Yes, you do that in settings.py
You just supply the db name, port (of postgres, 5432 by default), ip (of the linux server), username, and pw in your settings.
I'll try to delete cache
Ok I deleted cache and it's not working anymore. I tried earlier to do CTRL + F5 to reload without cache but site was still reloading. Thanks !
Yeah its ctrl shift r for hard reload
?
guys i have a problem my page is redirecting on all devices
did you adapt it appropriately?
Is there a common way in Django where to save for example a custom Mixin?
Can you elaborate?
What... does that mean.
Does postman provides good documentation for API. If yes why when doing some research, I found always that swagger and openAPI and few other are always more recommended.
It is a documentation that must be prepared for a front-end developer to ingrate the services in front.
I want to edit the LoginRequiredMixin , so I want to create a custom class but im not sure where to safe it
you mean save it?
i created an app called core which holds all these general stuff
example: https://github.com/IgnisDa/ocean-pv
Okay thanks
Does postman provides good documentation for API. If yes why when doing some research, I found always that swagger and openAPI and few other are always more recommended.
It is a documentation that must be prepared for a front-end developer to ingrate the services in front.
I've got a Django project I'm working on as my web development training, and while I'm decent in Python + backend/devops stuff, I'm struggling with the JS parts. I'm looking for someone who would like to contribute with some JS knowledge and learn/practice JS (and Django) together on the project. Shoot me a DM if you'd like to collab
What's your project, out of curiosity?
It's a SEO/marketing toolkit, I'm automating a lot of stuff I'm doing on a daily basis for me and my SEO peeps, and I'm creating a dashboard for it, but doing it with Django only without any JS has quite a few limitations hence why I'm looking for someone who's familiar with JS
Okay
How do i use html to request a file and python code to download it
Is there a way?
In my html page i click a button and python downloads it through response
Im using python cgi and ajax/jquery
But i cant find anything
I'm confused. You're using a solution already so what can't you find?
Or that's what you want to happen.
Hello there people of the internet, is it better to use react together with django, or just use normal html, css and javascript through the django templates?
For other related thing
Having a decoupled front-end like React or something is the more thorough and professional way to do it but you don't have to. You can just use Django templates and get by just fine.
Depends what you need, as always.
.info {
width: 80%;
margin: auto;
text-align: center;
padding-top: 100px;
background: #3e4c61;
}
how to I set the background color to the full section, without changing the width
but the functionality is pretty much same, isn't it? React is just more organised, right?
Not exactly. React does a lot of extra stuff, like allow for managing of state of objects/data, and refreshing aspects of the DOM as needed rather than the entire page.
display: block;
Not really @dense slate, i need to click the button, the file is generated in the server, and then its downloaded
Its not something static
ok, thanks
Ok so the content of the file can be dynamic?
Yes, but size will be always the same
.info {
width: 80%;
margin: auto;
text-align: center;
padding-top: 100px;
background: #3e4c61;
display: block;
}
```?
Yea I mean you would ajax a request to the backend, handle that on the server and return the data. then just download however you would normally do that on the front end.
I don't have any actual examples.
so if I want to make something complicated, that would always need constant data management, and active use of the plugins and stuff, it's better to use react?
yeah, that hsould work
nope
I would, yea.
The "then just download" is not working :(
i have the margin set to 80, but i cant change, but i want the background to cover it all
put the background colour into the body section of your css
I don't have a lot of experience with that, sorry. I'm actually going to be doing that this week - create a PDF from html and allow the user to download that. I just haven't done it yet (and am using a library)
Ty, appreciated
so then it ignores the 80% width
or use a separate class, like "container", and set the width to whatever you want there, so that it's more neater, and you can use it on several objects in your website, if the design is the same
oh yea, i may change that later on depending on how I want the site to look
Any answer
err <@&831776746206265384> Im not quite sure what this is
@native tide We don't allow recruitment here, please read our rules. Also... that's really racist
!mute 816978312756330500 3d We neither accept offers for paid work, nor casual racism here.
:incoming_envelope: :ok_hand: applied mute to @native tide until <t:1628956088:f> (2 days and 23 hours).
Please make sure you read and understand our rules and code of conduct.
hi lads!!
i want to update an object through this view. but i couldnt. you guys have any idea ?
i've tried the using '-' but it doesnt seem to work
My website 1 nginx conf file is rendering website 2 on my server. Does anyone know why?
Website 1:
# the upstream component nginx needs to connect to
upstream django {
server unix:///home/webserver/exo_dashboard/dashboard/exo.sock;
}
# configuration of the server
server {
listen 80;
server_name beta.exobot.xyz www.beta.exobot.xyz;
charset utf-8;
# max upload size
client_max_body_size 75M;
# Django media and static files
location /media/ {
alias /home/webserver/exo_dashboard/dashboard/media;
}
location /static/ {
alias /home/webserver/exo_dashboard/dashboard/static/;
}
# Send all non-media requests to the Django server.
location / {
uwsgi_pass django;
include /home/webserver/exo_dashboard/dashboard/uwsgi_params;
}
}
Website 2:
server {
root /home/webserver/website;
index index.html index.htm index.nginx-debian.html;
server_name exobot.xyz www.exobot.xyz;
location / {
try_files $uri $uri/ =404;
}
location = /arc-sw.js {
proxy_pass https://arc.io;
proxy_ssl_server_name on;
}
listen [::]:443 ssl; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/exobot.xyz/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/exobot.xyz/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = exobot.xyz) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
listen [::]:80;
server_name exobot.xyz;
return 404; # managed by Certbot
}
both of the websites render website 2
I want website 1 to render a django website
Can you give more information? Is it literally not doing anything (so maybe not entering the function) or is it giving an error (share the error)?
i figured it out !. i was supposed to do the arithmetic operation between brackts().
anyways thank you
So I am making a web page for a game that files outputs
that file has data the user needs to submit
The issue I'm having is finding a way to open explorer on the directory on upload button or through anchors
heyo
anyone there who can help me with this error
this error is throw on an async msg when i try to find by id in a mongoose database
Is this just a bug in Pyharm, or am I doing something wrong with the HTML? page displays fine, just that Pycharm is bugging me with this warning
(Django template)
What's the actual warning?
Oh sorry, it's just saying that the "closing tag matches nothing" although it should be closing the <dt>
I'm guessing that Pychamr Community can't parse the Django for loop and is thinking that the HTML is invalid, but that's just my suspicion
the <dl> tag is closed btw, just not in the image
On a related but divergent note...I have some complex template conditioning that appears to result in errors in PyCharm around tags. PyCharm is suggesting to remove a tag, but methinks there's a bug in their parser that means PC doesn't always nail errors. My experience is that I occasionally get false-positives...I'm getting a red-underline and "remove tag" suggestion and yet the web page renders perfectly...According to PyCharm this screenshot shows a web page that should be broken, and yet to my eye is rendering exactly as intended.
Yep sounds like what I'm experiencing, the page loads fine (not as pretty as that one) but Pycharm doesn't like the HTML
This is the end of the html file...
In all fairness to PyCharm, sometimes the conditioning and looping for a template can be really quite intense. There's a lot of things going on in the application layer to make that page possible. And I'm only using the presentation layer to filter/condition or loop. However, the net result is still some intense template layout.
How can I use aiohttp to make clickable buttons that trigger functions?
how do I send the contents of a text file through a flask websocket?
does anyone know? #web-development message
Sorry but I had to post this if anyone can anwer this, https://www.reddit.com/r/Python/comments/p2ndv0/python_webassembly/
Tldr yes, look at oxide, no its not for frontend
Python as a language is arguably the hardest language to try embed into wasm
Outside of shipping an entire interpreter with the wasm code
If you want to do frontend systems you're far better of just using normal js
And js frontend frameworks
Wasm in general is still very new and had many limitations which vary across browsers
Will wasm ever become viable as a frontend framework for production? Maybe, yew.rs with rust is probably the most promising, but that still requires interfacing with js and wasm binaries are still just massive blobs leading to slow timez
Will python ever become a frontend browser framework language with wasm? Almost definitely no
Would be nice tho, I like python a lot and I want it to be my primary and only programming language.
Trying to make an API with fastapi
How do I go about managing tokens? like generating/regenerating them and saving keys/secrets?
Often 1 lanuage is never enough, another lanuage may be better in situations than others.
E.g. Java and kotlin for android apps
Lua for embedded scripting
Swift for IOS apps
Js for frontend web work
Good day everyone, I am wondering how you all approach integrating your front-end with your back-end source without putting everything in the same project. For instance, looking to use React on a small portion of my site. How can I keep my React code in another project, but have easy access to development?
some kind of script that copies over the compiled javascript? But then you have to build each time?
A good question. I'm deep into a Django web application project with about 8 apps. I'll be using React for just 1 of those apps. All back-end development so far. I'll be curious to see what answers come forward...
Yeah I did it once before where I was lazy and just dumped it all into a package on my back-end. It just felt wrong and out of place
As for the direct answer, I've been making extensive use of the application layer to query the DB, and to set up the front end through context dictionaries.
It's working really, really well so far. But it's all text/file data. The final app for phase 1 will be an diagramming and that's a whole different bag
What is helping me is to develop all the apps that won't need JS in the back-end first. Get that down, and then focus on the final app from the front-end in.
I'm actually blown away by how fast you can build in Django when you get the hang of it. Just built a full on complex app in under a day.
hmm, I suppose I could make the api first. Front-end is just a quick admin dashboard to change some settings. So it'll have access to a very limited private api
Very nice. First project I did was Django. Probably did every bad practice in the book
This one I'm trying out FastAPI. So far liking it
Well I read two scoops of Django to get some best practices down. But I KNOW there's refactoring to be done. However, I plan on building a paid dev team for that once this goes to pitch
This channel so dead š¦ It's just you and me haha
I'm doing all my querying through views.py files. Likely not best practice for other devs working on this. But right now I'm the sole dev...
and it's working
tbh ActiveRecord patterns really promote you doing it in views.py so I don't think you are doing anything wrong
The thing is, once I worked out how to query and update the DB on form saves, you know, save the field they filled in the form, and did coding to update fields not showing...all I needed
phew
Only started using Dj this July...so ultra NOOB here
But the speed of dev in Dj is astonishingly fast
site looks good. Congrats. DId better than me on my first try
by second try is a monolithic abomination
This is a monolith. But it's fitting. it's a web app for business to improve quality and their profits. Built on 20+ years of consulting experience and tools I train. It's automating me as a business consultant.
The tagline. Complex Made Clear.
The vision. A business consultant in your pocket.
The entry-point. A free subscription to try it out.
Are you pitching me? š
Nah. Always curious to see reactions.
Besides, the entry point is free. There's nothing to pitch.
It's a business to business tool tho. Nothing like it out there that I'm aware of. The final app will be a diagramming one for something i call Collaboration Mapping. That's the BIG one. When I nail that...
In the meantime, I don't know a scrap of JS. I'll be learning that next.
But then, Apr 15, 2021 I didn't know a scrap of Python...so I figure I'm solid ;D
That's awesome man
I'm actually along similar lines of work, primarily in franchise restaurant operations
So, always curious to hear about React. It's the tool I'm hearing good things about for the front-end and diagrams
patterns are fairly similar to most businesses I find though
Oh really...
LanesFlow has a subscription tier for Consulting Agencies...
OK...I may be pitching you at some point. Interested in being an alpha tester?
Sure. I don't have decision making power for an app like this in full disclosure. Mid-level management here working on behalf of the franchisor
Hey...that won't matter...Friend req incoming. I'll follow up in a few weeks...
hey i have question how to use postgresql on django? i have been trying and download everthing like libpq-dev and still i can't use postgresql on django. Please help!, thanks
is psycopg2 not installing for you?
can you post your urls.py? Doesn't sound postgres related tbh
sorry your post/urls.py
it's still empty i just wanna prepare for database
rename urlpattern to be urlpatterns
That will atleast allow it to go past that first error
delete that screenshot
and change your secret
paste errors as text
screenshots are hard to read
see this
Ok so there's your postgres error. Its saying it can't connect. Did you install postgres on your machine or are you running it in a container?
i installed but i can't opened idk why
not a linux guy, but quick googling (and this would be distribution dependent) but make sure you start your service. an example I believe for ubuntu is pg_ctl start
ok repasting my earlier question so its not lost
Good day everyone, I am wondering how you all approach integrating your front-end with your back-end source without putting everything in the same project. For instance, looking to use React on a small portion of my site. How can I keep my React code in another project, but have easy access to development?
alright
const { Client, MessageEmbed } = require('discord.js');
module.exports.run = async(bot, message, args) => {
var pingembed = new MessageEmbed();
var editingembed = new MessageEmbed()
editingembed.setColor("#40E0D0")
editingembed.setDescription("Pinging...")
const diff = Date.now() - message.createdTimestamp;
let msg = (` š **|** Pong! **Bot Latency:** \`${diff} ms\``)
pingembed.setColor('#ff7100')
pingembed.setDescription(msg);
message.channel.send(pingembed)
}
module.exports.help = {
name: "ping",
aliances: []
}
```for some reason this command wont work
no error is provided in the terminal either
This is my command handler: https://hastebin.com/rabatiqobe.http
and its javascript
heh yeah that is a discord bot. #discord-bots is the right channel
I don't know about you all, but my website is making me hungry I think I'm almost ready to deploy
define āprojectā
you mean like Git repo?
you might wanna ask this in #tools-and-devops too
this is quite a devops question
ok I'll post there
but yes, essentially how to have them in different repos, but actively develop on them
Hey guys can someone show me some example code for getting a response dictionary and printing it to command line? for some reason when i execute print(reponse.POST) it prints a blank line
oh, linux guy. that makes it quite easy
for ubuntu (and probably debian too) systems, all you need to install those additional packages
apt update
apt install -y python3-pip python3-dev libpq-dev postgresql postgresql-contrib curl
apt-get install -y build-essential
plus your pip should have installed psycopg2
pip3 install psycopg2
(This library will not install itself properly until you installed the apt things above)
and that's basically it. then all is left to insert the right settings for connections
i have as default sqlite3
DATABASES = {
"default": {
"ENGINE": os.environ.get("DB_ENGINE") or "django.db.backends.sqlite3",
"NAME": os.environ.get("DB_NAME") or BASE_DIR / "db.sqlite3",
"USER": os.environ.get("DB_USER") or "",
"PASSWORD": os.environ.get("DB_PASSWORD") or "",
"HOST": os.environ.get("DB_HOST") or "",
"PORT": os.environ.get("DB_PORT") or "",
}
}
but in .env file I rewrite them with those ones to conect to postgresql
DB_ENGINE=django.db.backends.postgresql_psycopg2
DB_NAME=postgres
DB_USER=postgres
DB_PASSWORD=postgres
DB_HOST='127.0.0.1'
DB_PORT='5432'
you should be obiously having setup password for your database
password postgres is bad one btw š
How do I make a script know how to type in a specific place (say the Discord chat box for example)?
just use their API
every chat box is some channel
all you need to use their send function with providing in which channel to send the message
you can find and use discord chat box without using their API though
all you need to use the necessary Xpath path(Because essentially Discord is a website in Google Chrome). but that would be ridiculous way to do that. With API it has no point
Plz anyone refer me a beginner project for django
Todo application obviously
A bit more advanced can be something like Spotify
With users and liking songs etc
would you guys recommend graphql or rest, especially if I were to build an api with python
after having some experience with python graphql server libraries, I found out that they are really young and not mature enough. It will still take some time.
However, graphql promises a lot more than rest
Thnx for referring
Yes python and graphql have not played together well yet. The worst thing is that support is moving very slow. I made a PR adding docs to a graphql library and it has not been merged 3 months now. It makes me sad how the community is missing out on such a good technology.
how to make a date time filed in django models so that it take millsec also as a timestamp
how to make text color and font in flask.py
use css and html
Time to learn...InLine Formsets š
Are my python and web development skills enough for a good job
Or ds algo
And
As I'm 16 and ig good on development now working on django rest Framework so should i countinue Development or start with data structures
My recommendation...look for projects to build that solve valuable problems. If you've got an idea of the type of coding you'd like to do focus on that
Your project portfolio gives you something to show. The experience building those projects gives you depth to talk about
Can someone please let me know if there exists a job board in this server??
I do not believe there is a job board on this server. Recruitment is against the rules. Keeps it clean
oh okay thanks for letting me know.
I am making a website with a game, and I want to add sounds to that game but the sounds seem a bit delayed and they can't overlap, the game can require a few sounds per second. But the sounds will not play, or initiate (as in if I hit something, a sound plays, but if I hit something else as the first sound is playing, it won't play the second sound, even after the first sound is finished) until the current sound has finished playing.
Code
var gameOverSound = new Audio('/audio/player_lose.wav')
var enemyHitSound = new Audio('/audio/enemy_hit.wav')
var enemyPopSound = new Audio('/audio/enemy_pop.wav')
// then in some loops
gameOverSound.play()
//...
enemyHitSound.play()
//...
enemyPopSound.play()
Was hoping to ask some advise, just taking my first early steps into Django and was wondering on best practice.
Where should the data manipulation occur, within the SQL or bring it out into Pandas
with a view to exposing the results to the end user
hey guys, I have a problem in css of my website, I used position relative in the Todo List script, and when I click the add button on the top, it adds HELLO but also there is a blank space increasing in the bottom, which is the white area at the bottom of the image
do you have a link to this page?
and what is the problem with the white part again?
what do you want it to be
what do you expect to happen
what happens when you add a new tag
there are also no html or css code shown
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
.todo{
position: relative;
left: 290px;
bottom: 500px;
margin-bottom: 15px;
font-size: 25px;
background-color: aliceblue;
height: 43px;
width: 650px;
border-radius: 10px;
font-size: 20px;
}
.trash-btn{
position: absolute;
left: 670px;
top: 1px;
border: none;
border-radius: 5px;
}
.trash-btn:hover{
border-radius: 15px;
}
this is the css
can someone help with this basic q on Flask in #help-candy
when I type something and click on the add button, the white space increases, I dont want that to happen.....
is there any fix for that?
@sturdy sapphire what should I do?
i think you should provide the html too for easier reference
I had watched a couple of videos about web development they told us that we must know javascript for it, is that true? or python can handle that
yes, it is true.
I mean...
if you are backend web developer, then no, python is enough
but if you make back and front at the same time.
Then you need to know python and javascript at the same time too, preferably.
Technically you can make beautiful things even if you know only python + html + css
but knowing even a little bit of javascript will help anyway.
thanks
I have a question in #help-croissant
How do I get a user input from my html textbox and pass it to a variable in another .py file within the project? All online examples and SO answers simply "return" the value within the @supple flame.route function
(context django) when using custom user with all auth do you need to do email = models.EmailField(unique=True) as well if you are going to set ACCOUNT_UNIQUE_EMAIL = True?
@api_view(['GET'])
def test_prog(request):
data={'Age':16,'Name':'Aryan'}
return Response(data)
class TaskList(generics.ListAPIView):
queryset= Task.objects.all()
serializer_class= TaskSerializer
permission_classes=[IsAuthenticatedOrReadOnly]
throttle_classes=[UserRateThrottle,AnonRateThrottle]
filter_backends = [filters.OrderingFilter]
search_fields= ['task']``` in cbv we can filter ezily but how to filter in ```@api_view```
plz show how to do it by doing in def test_prog
bad name š
test_* is conventional way to name unit test functions
it is not in your case. you have a view function.
Guys should i learn django or flask? I have already know the basics of python
I want to use mongodb with it also
Which is more useful?
I imagine that there's a way to hook mongo up to almost anything.
Flask is really easy to get up and running with
Django doesn't even have an official Mongodb ORM since its nosql.
Among flask and Django I'd recommend Django though it's a bit more difficult
But it gives you more out of the box
MongoDB is used.
I'm sure it is
it is just has totally a different usage from SQL databases
don't mistake one for another
if you know basics, better to start with using Sqlite š
good for beginners
MongoDB has a native Python driver, PyMongo, and a team of Driver engineers dedicated to making the driver fit to the Python communityās needs. In this article, which is aimed at Python developers who are new to MongoDB, you will learn how to create a free hosted MongoDB database, install PyMongo, the Python Driver, connect to MongoDB and more.
I already knew sql
well, then it is fine to go with MongoDB, cool thing to know too
I still can't find a time to expand my knowledge in this direction š
why not š you can
there are libraries for python integration with mongo
multiple ones
So in conclusion.... should i learn flask or djangoš
You can write a basic flask server in 5m
try that and if you don't like it try django
flask is good for starters, django is good for real work
Based on functionality?
flask follows micro framework approach
you have nothing at the start and you add micro libraries of its functionality.
good for starting learning curve I guess
django is having batteries included approach
everything is already enabled, you are like train on the rails (hehe ruby on rails)
you need to navigate through its documentation a lot in order to not reinvent the wheel
So is there anything that one can do but the other cannot.
?
Smthg like shortcomings?
mm there are things actually.
main difference = Django offers already made Admin/moderator thing easily being made
+its good ORM for SQL usage
for Flask you choose your own SQL ORM thing
Flask made recently a step to become Async friendly framework
it is a bit too fresh probably though
Django made a step too, but a bit behind, since it can't transfer its ORM to asyncness yet
Hmmm
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '<h1>Hi There!</h1>'
if __name__ == '__main__':
app.run()
That's a flask web server
Still needs some consideration
usually people...
who don't choose Django...
they choose Fast API
it is sort of...
having a lot of things already enabled for you too, but from a different sphere
So which one do you prefer personally?
Fast API is fully async friendly framework, without ORM already installed, but as far as I heard it has almost setup REST documentation tools
I tried only Flask, Quart and in love with Django
I work with Django extensively, but eyeing quite a lot Fast API
wishing to try Fast API
Hmmm i see......
I think i will go with Django then
Thanks for the info mate
I'm going to sleep now byeee
Does anyone have experience sending mail from the backend?
Some of the stuff that I've read says skip doing it yourself through smtp and use a service like SendGrid instead
Does anyone know if this is good advice?
I am in a nutshell
my suggestion is to use ariadne for APIs these days, I have found graphQL much nicer to work with than rest
https://fastapi.tiangolo.com/
fast api claimes the speed of Go
FastAPI framework, high performance, easy to learn, fast to code, ready for production
I wonder how true those words are
it depends on how you measure and is a completely meaningless number
anyway, when you are going to use some custom database connecting library, I think Fast API could work better than django perhaps
like GraphQL I guess, or async postgres library
graphql is a replacement for rest, not for a query language
though afaik there are databases that support graphql
as far as I heard I am supposed to get some database like Neo4j or something like that
for graphql
no need
hmm
I have done a graphql API running on CGI using mysql as the db
it wasn't very fast (because cgi), but it does work
considering multiple caching instruments, perhaps.
caching database requests with redis
caching incoming requests even earlier with varnish
enough of things to cache and speed up š
now yes, there are databases that work well with graphQL, but well, you can use whichever one you want
web framework benchmarks are not a good way to pick a web framework
also, they are really easy to make misleading
yeah, Django is great
rapid blazingly fast š
like... when you are going to develop a web chat... there is Django channels thing and e.t.c.
even ariadne has django integration, so you can use the django ORM for a graphql api
yeah, I saw the guys in imagine had a template
to presetup django with GraphQL as an option
with already made 100% coverage
cools guys.
I think I saved for myself their example, just in case to dig whatever they made š¤
that is one thing where django feels a bit lacking compared to sth like springboot, testing. But at the same time, I did not do a lot of django automated testing, so it may be better and I just haven't found the correct solution yet
I feel myself good, when testing in django
pytest
coverage
mypy if I wish
whatever else I need? everything works.
if standard testing tools in Django aren't enough
they are extended with Django Rest Framework
it provides everything you need for testing of APIs I think
probably I guess it would be a bit contradictory to use them with GraphQL, or not š¤
I did not use springboot to compare though
what would you recommend as a backend besides python+django to cover most of other situations?
Go+Jin I think? / Springboot + Java ? Ruby on rails? Something else?
Hello, so I'm a beginner and I need someone to please help me out as an accountability partner, we could be friends here and grow together . Thanks in advance
what I really liked was ruby on rails, but that is actually resource hungry enough to matter
Golang is quite recommended for devops people
since I go with being backend+devops
perhaps some Go backend could benefit me better, since it would benefit me being as devops too
I am very opposed to some solutions go takes to problems (byte sequences are not text, no matter how hard you squint), but it is indeed a good language to know for devops
whats that
i use graphene lol
ah, it is similar
plus Go is quite fast one š
it could be fill the niche
if you need fast and web, there is rust
i feel that python servers' speeds are fine
yeah, haven't ever had any issues
but it has you write the schema and bind the resolvers to the schema, it does not generate the schema from a class
see graphene
couldn't tell you whether that's a better approach than writing the schema in python
I am a bit worried that Rust is not even mentioned in any popular lists
I guess I will compare available job vanacies
in Rust and Go
to make a choice
oh, for jobs for sure go
i probably won't learn anohter language other than python and js
Rust is still niche
speaking of which
Golang will serve me better I hope to remain popular
im using svelte nowadays
yeah, I recently tried svelte and I am a fan
the right mix of react components and old style MVC separation of concerns
ive been thinking about trying out svelte for my next project
do you like it? would you recommend it?
im a vue guy and svelte looks easy
and svelteKit looks really interesting
yeah, so far the best frontend framework I have used
Does svelte have any diagramming chops?
no idea
I'm stuck on Django Inline Formset and this error: "ManagementForm data is missing or has been tampered with. Missing fields: VOC-TOTAL_FORMS, VOC-INITIAL_FORMS. You may need to file a bug report if the issue persists"
code?
Posted forms.py and views.py snippets to #āhelp-coffee
Will keep on researching this one...stumped
Definitely, it's super great
Yeah, and because it was made by the svelte core team rather than a third party, it's really actively developed and supports everything
Worked it out...Inline Formsets are BELONG TO US! š
Can I just say how profoundly brilliant I find crispy forms to be!
This...so. much. this!
Hi I want to do a small website and i heard that Flask is better than Django for small project, what do you think?
It's going to be a website just for fun
What is a MVP in Django?
if you just need some basic routing then flask is the way to go
Yeah but when you start using even a basic database, I have a feeling django is easier to use
Because of migrations and no need for seperstely installing SQLAlchemy and things like Flask-Migrate
hai can I get help pls
So I have a text file thats gonna be constantly updated and want to receive the contents near instantly. I got websockets kinda working but its still not updating when the text file changes
For someone who is learning back end development, learning html and css is important?
for a career or just a hobby?
career absolutely hobby you only need to know enough to make sure the back end is working
That's some nice CSS
@gloomy comet Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!
Thanks š My first Django project.
hello can you help me, i have some trouble about post method to api by library requests and urllib, the code not works and i dont know about mistakes.
When i'm trying with postman it works
how can solve this problem?, thankyou very much
this is my code with using library requests
this is my code with library urllib
and this is i test from post man. it works
Anyone knows how to create a domain web server for vscode local host can help me pls thank you
can someone help me out hosting a flask python website into pythonanywhere?
amazing
I have a project with
- Two python processes (web + worker)
- Redis
- Mongodb
Where can i host this ?
Is aws ec2 a good choice. i would love to hear about a free option. so that i can test this out. Thank you
I'm having trouble setting up uvicorn through cmd. says could not import module "working"
i want to user to change username but when i want to write the username that already existed the clean_username method not working and thus giving IntegrityError at /users/profile-edit/ UNIQUE constraint failed: users_user.username
HOW TO QUERY IN clean_username SO THAT IS SHOW ONLY USERNAME ALREADY EXIST ValidationError
class UserEditFrom(forms.ModelForm):
username = forms.CharField(label="",max_length=254,widget=forms.TextInput(attrs={'id':"user-name",'type':"text" ,'class':"form__input" ,))
def clean_username(self,*args, **kwargs):
username = self.cleaned_data.get("username")
if User.objects.filter(username=username).exclude(username=username).exists():
raise forms.ValidationError('username is alraedy taken try another one')
return username
If anyone's got experience with Django and Django-Graphene, please check out #š¤”help-banana and shoot me a ping. Getting weird issues at the start. :/
use data=payload instead of json=payload and remove the content type header when you're using requests
put your stylesheet below the bootstrap 1. this will make your styles take precedence
Someone may have tutos or codes to implement newsletter in django app blog? and make it work when someone subscribe with his email?
How to get requests from a drop down select box?
Apps arent loaded yet??
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
This happened after I deleted my database, made a new one and set AUTH_USER_MODEL = "account.Account", account is my app and Account is a class in its models.py
i wouldn't tamper with Django's auth stuff
but if you are
have you added apps to INSTALLED_APPS?
i had to buiild a custom user model
it has something to do with my postgres table im sure
and is your AUTH_USER_MODEL after INSTALLED_APPS?
no its before
there's your problem
the apps literally haven't loaded in yet
so django has no clue what your talking about
move AUTH_USER_MODEL to the end of the file or at least after INSTALLED_APPS
I did, it still shows the same error
have you ran the migration commands
although your reasoning makes perfect sense to me
yeah
i just did, and same errors
is your postgres server up?
itis
hm
it worked
i actually had imported accidentally account before installed apps declaration
happens to the best of us lol
it should not have been a problem but
to be honest, theres this weird thing happening with me
my files have erroneus lines that I dont remember writing
its almost spooky
its highly unlikely but, you know what they say
when you rule out the impossible, whatever remains, however improbable must be the truth
my laptop is possessed af
sell it on ebay and don't mention its possesed. when it gets sold, share the reaction from the buyer
lmao i love my it no matter what
i aint sellin it even if it automatically shuts or starts
How to get requests from a drop down select box? In flask
Where should I ask question about fbprophet? I wanted to add legend to the plot
@odd root ask here
@sleek pine request.form
will it work? Lemme try
yes
my login is broken!
when i try to login with my superuser it says Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive.
Does anyone here know how django's F() expressions work?
reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed = F('stories_filed') + 1
reporter.save()
The docs says that the F class overrides the standard Python operators, but I dont understand how. Like, is the assignment operator (=) overriden? Or how does the F instance know about which Reporters entry to look at, and even on which model should it search?
Also how can you just temporarily override operators?
you can override some operators using some special class methods like __add__ __sub__...
https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types
and you can define how that operator should work and what it should return
Hi is there some change in Github Policy today?
Hello
I made a custom user model, and i am facing the issue that password is not being encrypted when a new user is added
and im not even able to login with that new user
Alright so turns out you can only login when the password is hashed. They should have mentioned this in the docs.
I just typed wrong password. then I tried to log in as token. I can't install cli even
When you're trying to push in git, you can't use your password in git anymore
You'll need to use SSH or a PAT
#help-kiwi If anyone would like to answer a simple question about Django templates
Just logged in. Do you still have that question?
http verbs are confusing. guildconfig/{id} alters a config but can't change the id. Is that put or patch?
I'm thinking put since you need to supply the entire body?
Yes I am still wondering if it's possible to have something like a 'global variable' that I can use in my templates, for now I have just changed it so that all mentions of the site title are in the base template html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>PyBlog - {% block title %}{% endblock %}</title> </head> <body> <p> <b><em>PyBlog - {% block page_title %}{% endblock %}</em></b> | Then in other templates I do this html {% block page_title %}{{ page_title }}{% endblock page_title %} where page_title is passed in as context from the page specific view function. Here is how that looks on the index page
Maybe have it in a file that you import into each view file?
Load it as a context within each view.
I am not aware of another way of doing this...
Ahh ok, yeah I guess that is probably the simplest way to do it. I was wondering if there was some sort of way to pass it from the base template, but that will work too!
However, template inheritance does take care of presenting it front end. But the context var needs to be in every view. Importing it would save a bit of code
current year for the footer is a good use case for that. Although, I build the var in each view file. So I've not tried what I suggested.
something like views.py ```py
from django.shortcuts import render, redirect
from datetime import datetime
...
DATE = datetime.today()
Is that what you do for the footers?
I suppose this will work, it's easy enough to just pass this as context in one of the views (I only have one views file right now anyways)
Sorry was afk. Yeah...pretty much. I'll load the global at the top, and then load the year as a variable through context. That way, the year will always be current.
Just finished dashboard prototype design today... I welcome any UX feedback...
To be specific, I use the following
import datetime as dt
CURRENT_YEAR = dt.datetime.now().year```
Looks very clean! I would maybe move the Profile and Subscription buttons closer to the sign out button, I think it might be better to have one side of the header for Tools and resources and one side for account related actions. But over all looking very good! Is this all possible with just html / css / django? Or are you using Javascript etc..?
Just Django/html/css for now. Working with React/JS for the 8th app
sounds like something that will break when the application is running as the year is incremented
it's not really supposed to be a constant
How so? When the year is calculated with each page view?
Fair point. I could de-capitalize. I originally had it that way ironically
I guess if the server were running in production, and it's New Years Eve it would be a problem, is that what you mean?
I mean, unless you restart the app exactly at 00:00 on Jan 1, it will think it's still 2021
yeah
ahh yeah that is a good point...
So I'd need to pull the year calc into each view function?
Yoo check this out https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#now
I love django already
There's a template tag for that
Lovely
Oh these are nice... https://docs.djangoproject.com/en/3.2/ref/contrib/humanize/
Thanks for the feedback. Here's the shift. Moved Subscription under the profile menu too.
Yes, Humanize is very useful.
Anyone here well versed in html or css or in general webdesign? Trying to master webdesign (html, css etc etc) and would like to know what I should prioritize to see sustainable progress I know basic html tags and a couple css style selectors and how classes work somewhat and would like some outside input
rather than
"parts" of HTML/CSS
you should focus on how to do things
I have bugs in my django project can anyone help me please
If I complete the project I will shortlist for interview pls help me
Hi there, I'm trying to figure out how to configure a custom user for my DRF project. I have attached my directory structure.
I have created a custom user like so:
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
pass
Added my application to INSTALLED_APPS:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
# custom apps
'apps.api'
]
And tried to change the AUTH_USER_MODEL like so:
AUTH_USER_MODEL = 'api.User'
However, I'm getting the following error:
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'api.User' that has not been installed
I have tried many ideas, but it still won't work. Could you help me?
Thank you!
AUTH_USER MODEL='apps.api.User'
I also tried this and getting another error.
Fortunately, I have solved the issue by creating an __init__.py file in the models directory, and added the following line to it:
from .User import User
Then it worked.
Hi myself Onkar and I am working on a Django Project. I am working on implementation of encryption techniques. This is my first project in Django.
Can anyone help me with the file handling in Django?
Condition: I want to encrypt file in my system and then immediately give user the key and encrypted file. I have code for file encryption using Fernet. Now all I need is solution to how to open the file in Django site??
def generate_key():
key = Fernet.generate_key()
with open("secret.key","wb") as key_file: key_file.write(key)
return key
def load_key():
return open("secret.key", "rb").read()
# keygeneration done
# encryting the file
def encrypt(filename):
key = load_key()
f = Fernet(key)
with open(filename, "rb") as file:
file_data = file.read()
encrypted_data = f.encrypt(file_data)
with open(filename, "wb") as file:e
file.write(encrypted_data)
# decrypting the file
def decrypt(filename):
key = load_key()
f = Fernet(key)
with open(filename, "rb") as file:
file_data = file.read()
decrypted_data= f.decrypt(file_data)
with open(filename, "wb") as file:
file.write(decrypted_data)
key = generate_key()
file = __File-Name__
encrypt(file)
print("Your file has been encrypted.")
print("Your key for encryption is: ")
print(key)
decrypt(file)
print("Your file has been decrypted.")
This is my encryption code
why does django need {load static}?
why is simply using images and other files not sufficient?
Hello i got doubts in django DRF
I'm working on this book, https://pgjones.dev/tozo/, that I aim to show how to build a production quality web app with a Python backend and React frontend starting from scratch. As well as building the app it includes how to setup your local computer, remote repositories and deployment. It has a companion codebase, https://gitlab.com/pgjones/tozo and the app itself is live at https://tozo.dev.
I'd really like to talk to you if this is what you are learning at the moment - specifically I'd like to know if this book makes sense, what it is missing, and whether it helps.
Hello everyone, This doubt is about Django REST framework.
I am currently building a web app API from scratch. I'm totally new to django and web development. I have three models and each of them are linked in this order 1-2-3. I have serialised the data like the below code.
what I actually want is to make a API output like below:
Models1 {
pass
model 2 {
pass
model3 {
}
}
}
and i want endpoints like this :
/api/v1/anime
/api/v1/anime?genre=
models.py - https://gist.github.com/jokerhacker22/6951d8667a32b069708884a296357c28#file-models-py
serializer.py - https://gist.github.com/jokerhacker22/219453bf3fdcbbeed316b98ab04cfebd#file-serializers-py
I am looking forward to get help from the experts here.
thanks in advance
How to dynamically add / remove input fields in Django anyone help please ?
I am new in Django
you mean adding and removing input fields in admin?
i want to add and remove input fields in html using a button
like want to add a value then i have to click a botton to add a input field or if i want to delete a field then i can do that using a button
that's some kinda intermediate level yet i'm also new in django
i can help with some basic one's
then can you make this in html https://www.youtube.com/watch?v=6N4OmsfwfdU start from 11:30
Python Flask Add Remove Input Fields Dynamically with JQuery Ajax and Mysqldb
Source Code : https://tutorial101.blogspot.com/2021/01/python-flask-add-remove-input-fields.html
you are building this in front end?
i use django for backend only, tried react once for front end
front end is for user and back end for us
that html page will be connected to sql to store values
i didn't understand
You are making a page which connects to the sql server where you can edit data like models right?
Django default admin panel does this
connects to the database, you can view or edit data and you have security there
because that's defult sql in django
default*
i use postgreSQL alreday
what database is used in settings.py only behaves there
you can't
well, you can, but not easily
that sort of dynamism would be much better done with JS
on the frontend
idk JS š¢
please someone answer this
?
I wouldn't tell you to use JS
if it wasn't necessary
HTML and CSS alone
only allow you to create static pages
I actually don't really get the question, sorry
š¢ š¢ š¢ š¢ thanks for the help bro can you please suggest any video or page so i can learn that
look at my models and serializer sir, i want to make API endpoint where my models should be nested
like 1-2-3
uh...
not really, sorry, I don't use those
oh
nest the serializers
how?
ok thanks bro
class ModelASerializer(serializers.ModelSerializer):
b = ModelBSerializer()
class Meta:
model = ModelA
class ModelBSerializer(serializers.ModelSerializer):
c = ModelBSerializer()
class Meta:
model = ModelB
class ModelCSerializer(serializers.ModelSerializer):
class Meta:
model = ModelC
fields = '__all__'
like this
and one more thing sir
i want to make a querystring in api endpoint the query will be one of the objects in the model
can you elaborate
with an example
let me sir
i am building a anime backend API
i have episodes models
season model which is foreign key to episode
and anime model which is foreign key to season
and as ya said i have made a enpoint like this /api/v1/anime/
where all anime will be displayed
here i want to filter anime which is higher in rating
rating, popularity , created_at and start_date
class Anime(models.Model):
"""Base Class for Anime models"""
name = models.CharField(max_length=80, blank=False, null=True)
slug = models.SlugField(max_length=50,help_text="Slug name", null=True)
original_name = models.CharField( max_length=70, help_text="Original Name of the Anime(optional)", null=True, blank=True)
description = models.TextField(help_text="Desription about anime.")
cover_image = models.ImageField(upload_to="Anime/cover_images/", verbose_name="Anime Cover image")
bg_image = models.ImageField(upload_to="Anime/bg_Images/", verbose_name="Anime Background Image")
created_at = models.DateTimeField(auto_now_add=True)
genres = ManyToManyField(Genre)
rating = models.FloatField(
validators=[MinValueValidator(0), MaxValueValidator(10)],
)
popularity = models.FloatField(
validators=[MinValueValidator(0), MaxValueValidator(100)],
)
author = models.CharField(help_text="Author name of the anime", max_length=50)
country_of_origin = models.CharField("Country Of Origin", max_length=20)
start_date = models.DateField("Start Date")
end_date = models.DateField("End date", null=True, blank=True)
status = models.IntegerField(choices=RELEASE_STATUS, help_text="Current status of the anime")
seasons = ForeignKey(Season, on_delete=CASCADE, related_name="animes")
staffs = ManyToManyField(Staff)
studios = ManyToManyField(Studio)
def __str__(self):
return self.name
class Meta:
ordering = ['id']
verbose_name_plural = 'Animes'
WTGF
my anime model
i just want to filter the enpoint with querystring
sounds cool
Oh thnx
so like
if I get what you're saying...
you want to extract optional arguments passed in the query string
and possibly use them to filter the returned results?
you can get them
from the request
request.query_params
that would be a good start
(in your view)
class EpisodeViewSet(NestedViewSetMixin, ModelViewSet):
queryset = Episode.objects.all()
serializer_class = EpisodeSerializer
class SeasonViewSet(NestedViewSetMixin, ModelViewSet):
queryset = Season.objects.all()
serializer_class = SeasonSerializer
class AnimeViewSet(NestedViewSetMixin, ModelViewSet):
queryset = Anime.objects.all()
serializer_class = AnimeSerializer
this is my views
I tried this but don't have any idea how to present it in urls.py
from rest_framework.routers import DefaultRouter
from rest_framework_extensions.routers import NestedRouterMixin
from api.views import (AnimeViewSet, EpisodeViewSet, GenreViewSet, NewsViewSet,
SeasonViewSet, StaffViewSet, StudioViewSet)
router = DefaultRouter()
router.register('episodes', EpisodeViewSet)
router.register('season', SeasonViewSet)
router.register('genre', GenreViewSet)
router.register('news', NewsViewSet)
router.register('Staff', StaffViewSet)
router.register('studio', StudioViewSet)
class NestedDefaultRouter(NestedRouterMixin, DefaultRouter):
pass
router2 = NestedDefaultRouter()
animes_router = router2.register('animes', AnimeViewSet)
animes_router.register(
'seasons',
SeasonViewSet,
base_name='episode-seasons',
parents_query_lookups=['episodes']).register('animes',
AnimeViewSet, base_name='episode-seasons-anime',
parents_query_lookups=['season__episode', 'season']
)
if you're using generic views
then
you need to use...filters
Django, API, REST, Filtering
this
or write a non-generic view
yw! š
@cerulean badger did you figure it out?
figure out what
pytube
yea I just looked up docs
alright
why?
I was gonna help you
I am wanting to setup a database scheduler based on celery, similar to django-celery-beat but specifically for Flask. Does anyone know if there is a library / example of this?
@austere relic
so can you help me display the reference webpage
I still don't understand what that is
at least the webpage?
if you wanna display a webpage open the url in your browser?
Hey! Would anyone be up for helping with a Flask project?
I am completely new to using Flask but would love to finish creating a web application but I am a little stuck š
just ask
@austere relic any ideas on my question above?
I'm really sorry, but I've neither tried celery nor flask
ok thanks
Thanks, does anyone know how I can create quizzes using Flask with a nice interface that allows for users to click one of the options and see if the answer is correct? And have the ability to add questions too....
sounds like something you can do purely client side
oh, except for adding questions
True, I am just not too sure where to start with programming the functionality....
well, you know how to make a header that says "QUIZ", which is a start
so what exactly are you in doubt about?
Yes, I am not sure how to create an interface that as 4 different options come up in boxes and be able to select them. Or how to have a form where you can input in questions. I am really sorry, I am quite a beginner!
Sounds cool
Are you comfortable with HTML? JS?
No, only really Python unfortunately, though I have messed around a little with HTML.
alright well, you can get away without using JS
using the form element
however, I don't know how flask handles forms, so can't help you with that
Django is better in handling data
Thank you for the link, looks great.
I've heard a lot good things about django
Yeah
i dont have any big issue but sometimes i face problems while i work in drf in making exceptions
local variable 'serializer' referenced before assignment```
@api_view(['GET'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def detailview(request,post_id):
if Post.objects.filter(id=post_id).exists():
try:
q2=Post.objects.get(id=post_id)
serializer=PostSerializer(q2,many=False)
except Post.DoesNotExist:
raise Http404("NOT FOUND")
return Response(serializer.data)
Can someone tell me how I make AUTH_USER_MODEL for my User model
I have app named api which is installed in settings and I have models directory inside the api directory and in models directory I have accounts.py file having User model
It happens because your try block fails then the raise is executed. After that the return Response gives that error since serializer is not defined at that point.
Move the return inside try
1 shift ohk done
Create api/models/__init__.py and from .account import User inside it
now py AssertionError at /69/ Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>
Yesh thanks sir but I crrated accounts app inside api app for workaround for now
Django doesn't know how to convert exception to responses
ohh
can u change it on my code and give me
@api_view(['GET','DELETE'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def detailview(request,post_id):
if Post.objects.filter(id=post_id).exists():
try:
q2=Post.objects.get(id=post_id)
q3=Post.objects.get(id=post_id).delete()
serializer=PostSerializer(q2,many=False)
except Post.DoesNotExist:
raise Http404("NOT FOUND")
return Response(serializer.data)```
this is current code
ohk btw one last question that is in my mind @versed python
btw fixed that exception error
yeah?
u can see code
In that q3 is to delete and my models are properly configured with foreignkey to identify which user is filling the form/post request
So i want only that user can delete only his/her Posts
I have done kind of same thing in e-commerce site so he/she can see only his/her order history
But it was ezz in that bcez i used for tag in html n all but in rest api we don't use html templates so how can i do that
@versed python
just pass that in the function parameters