#web-development
2 messages ยท Page 177 of 1
if you don't mind me asking what does it do?
Want to DM quick? Can share some screenies...
no worries. ๐ Figured I'd ask...easier to show pics with words
done
try now
Joy is...testing UserPassesTestMixin and seeing the 403! Love me some Class Based Views!
hey need help
in production mode i was using staticfiles_dirs and set up my urls in html according to that
but now in production its asking for static_root
and after running collect static
there are hell lot of files and now i cant change the url one by one in templates
what should i do
can someone please help me with satitic_dirs
i have downloaded the template which is free from web
i have added STATIC_URL = '/static/' STATICFILES_DIR=[ os.path.join(BASE_DIR,'static') ]
<html lang="en">
<head>
<title>Travello</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="Travello template project">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="{% static 'styles/bootstrap4/bootstrap.min.css' %}">
<link href="{% static 'plugins/font-awesome-4.7.0/css/font-awesome.min.css'%}" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/owl.carousel.css'%}">
<link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/owl.theme.default.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/animate.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'styles/main_styles.css' %} ">
<link rel="stylesheet" type="text/css" href="{% static 'styles/responsive.css' %} ">
</head>
<body>```
i have puted all static thing but still it is not showing me any css on the webpage
๐ฆ
how do I add a "following" relationship in Django? I've created a Profile model with a OneToOneField to the Django User; now I'm wondering if (and I ask you: how) I should use a 'following' ManyToManyField in the Profile, or if I should have a separate Following model with foreign keys to two different users (if so, how to ensure the fk's ARE different?)
what do you mean "following"
like in the social media sense?
yes, I'm making a simple Twitter "clone"
Where have you stored your static files in?
I'd recommend you use some third party Django packages to do this, they are well implemented
I see
well, I was trying to implement this as a learning exercise for Django itself, but is there any such package in particular that you recommend?
guys, should I ignore the media folder from Django for the github repository
Probably yes
None that comes to mind. Just search and use the first one ๐คทโโ๏ธ
M2M will work fine
or if I should have a separate
Followingmodel with foreign keys to two different users (if so, how to ensure the fk's ARE different?)
this is what M2M does
with an additional constraint that both values must be unique together
sometimes you want to add additional info to the relationship
in which case you can specify a through table in the M2M field
and define your own model for this
- whatever columns you want
e.g. you might want to have "muted follows", where you nominally follow someone but don't get notifications
in which case your following table will have 3 columns
from_id, to_id, and muted <- this is a boolean
then you can express queries like "get me all the to_id values (and hence users) for this user for which muted is False", or, in other words, all this user's followers who have not muted them
in static folder
it is working but images are not loading
@versed python
do {% load static %} above the template this can work
i did
the problem is it is not loading images
all static is css is working
but images
oh
Can anyone help me to Run a python script from url in terminal?
Hey guys so
I cannot manage to access or specify the path of this html file in my firstApp/view.py file
I think i should us the os module but dunno how, never used it
where is the html filed stored?
from what i know django usually has a preset path that goes through ---> templates/app_name/htmlfil.html
here
I mean, I could just move it in but the problem is different
what is the problem?
the map is not static
its values are being updated
the values come from by scrapping data fromhttps://www.worldometers.info/coronavirus/
Live statistics and coronavirus news tracking the number of confirmed cases, recovered patients, tests, and death toll due to the COVID-19 coronavirus from Wuhan, China. Coronavirus counter with new cases, deaths, and number of tests per 1 Million population. Historical data and info. Daily charts, graphs, news and updates
This is the command that generates the file
I tried to find a way to specify a math that can save this html file but
I could not, the library name if 'folium'
it automatically generates this html file here
well with django i think you can overwrite where it looks for templates in settings.py
yeah I tried finding that
but I thought it would affect other templates
then I will have to change the path of other templates in views I think
pain in de butt....,
if only I could specify where I want the html file to save, it would be done
how come there isnt any way to specify the path when it saves that file for you?#
what did you do?
was that it lmao
I tried it and it worked lol
i thought you already tried that bruhhh
I spent 1h googling and looking trough the documentation of folium and django
i tried to pass it as a seconda rgument
lol
ty for ur time
its good
If anyone's interested, I ended up just implementing a generic AuthenticatedRequest and hinting with [FooUser] or [BarUser] on a case by case basis:
from typing import Generic, TypeVar
from django.contrib.auth.models import AbstractBaseUser
from django.http import HttpRequest
User = TypeVar("User", bound=AbstractBaseUser)
class AuthenticatedRequest(HttpRequest, Generic[User]):
user: User
from core.types import AuthenticatedRequest
from foo.models import FooUser
class FooSpecificView(generic.TemplateView):
request: AuthenticatedRequest[FooUser]
There's probably something you could hack up yourself, but why?
Python has such a rich package ecosystem, you should use it to your advantage.
if form.is_valid():
user = form.save()
profile = Private()
print(form.data)
profile.User = user
profile.Address = form.data.get('Address')
profile.Phone_Number = form.data.get('Phone_Number')
print(profile)
profile.save()
messages.success(request, "You're account have been created!")
return redirect('signin')
Any idea why it keeps returning NOT NULL constraint failed: Private.Address
Guys I need a little help
hmm ig it's not sending to db try to print in downwards + it's type
yes ask plz
yo im using the google research thing and dont know why this isnt working
I'm really stupid, it's address* in the models. Thank you man
I am new to web dev and want to make a dashboard for my bot but I don't know what should I use
thats what i was thinking but later i saw
u made instance Private
and i was thinking u might be doing by another way
but remember
best way to debug is to print where the code breaks
and print type
๐๐ป pls help
Help
even idk what's it
what kind of dashboard can u explain in detail plz sir
ohk what r u trying to do
i am trying to make my text colored
A dashboard with all the info and cmds of bot and can connect to the users and guild and can show statistics etc
@dusk portal
yes
umm can be done by all frameworks django flask fastapi
What will be the best in features and ui
i recommend django cez it's title The framework for perfectionist with deadlines
just start learning dont waste so much time thinking
Ok django at backend but what should I use in frontend
just learn framework and think about it on free time and later when u start making dashboard just write on a page whole features and make accordingly
html css js simple
if u dont know js its ok
if u dont know css copy paste
xD
Well js can work with a python bot??
Heard for the first time
u said website ;-;
in dire need of help ๐๐ป @dusk portal
@dusk portal @dusk portal
html css in frontend django or flask in backend
tell me what u want to do
Only html and css or other there are other options too?
u can use react angular or vuejs
Aren't they js
these are one page technologies
they are framework's of js
So how will I use them with my bot ๐ญ๐ญ๐ญ
angular is now on typescript ik ik but others are
u made bot on which lang
Python
i want to make my text colored
;-; what's the sense of doing that
;-;

fun ?
Oops wrong reply
want to make it look pretty
bruhh!!!
what's the sense to see ur code pretty , in code pretty means optimized ig u were talking about the frontend
lol
yes
whats IDE
yes
and that doesnt matter
the more ur code looks ugly
open inspect element of yt
its x100000000 ugly
but result it awesome
doesn't matter how ur code looks what matters is the result
noone see noone cares about code
how to make output colored?
Not exactly
They can be used for SPAs, yes, but they also work perfectly fine in multi-page applications.
@calm plume explain him sir plz , im gonna cry now
That's why frameworks like Next, Nuxt, and SvelteKit exist.
In the terminal?
You could use ansi escape codes I think
๐ ๐๐ป
he said he want to beautify the code i cant get the reason
why would anyone want the code to look pretty
i have heard about optimization
not pretty

i was using colorama module is that ok
That's fine
But that's only for the terminal, right?
whats terminal
Uhh, how are you running your code without the terminal?
What text?
This is off-topic for this channel, why don't you claim a help channel and ping me there? See #โ๏ฝhow-to-get-help
Add a colorama.init() after the import
You'll have to import it ofc
ive made a subclass of djangos group class called community and im wondering how I can access the the subclass instance instead of the group instance when making queries
anyone have any ideas?
can someone please help me out
i don't understand why django is not loading my image files
Do you have a github repo?
from django.db import models
from django.contrib.auth.models import User
class FileUploader(models.Model):
file_input = models.FileField(upload_to='public/uploads/')
uploaded_date = models.DateTimeField(auto_now_add=True)
last_edited = models.DateTimeField(auto_now= True)
uploaded_by = models.ForeignKey(User,on_delete=models.CASCADE)
How do i save the file_input to public/uploads/svg
After converting the input image of png/jpg/gif to svg??
Can anyone help?
i got the images
but for this one i'm confused
<div class="background_image" style="background-image: {% static 'url(images/travello.jpg)' %}"
where to put static for this one
It's correct. Just add a url({static 'whatever'})
i didn't get u friend
html :o
Invalid block tag on line 457: 'static'#''. Did you forget to register or load this tag?
Request Method: GET
Request URL: http://127.0.0.1:8000/home/
Django Version: 3.2.5
Exception Type: TemplateSyntaxError
Exception Value:
Invalid block tag on line 457: 'static'#''. Did you forget to register or load this tag?
Exception Location: C:\Users\nawin\.virtualenvs\djangoprojects-rmJaG_g2\lib\site-packages\django\template\base.py, line 531, in invalid_block_tag
Python Executable: C:\Users\nawin\.virtualenvs\djangoprojects-rmJaG_g2\Scripts\python.exe
Python Version: 3.9.6
Python Path:
['C:\\Users\\nawin\\OneDrive\\Desktop\\djangoprojects\\tubers',
'c:\\users\\nawin\\appdata\\local\\programs\\python\\python39\\python39.zip',
'c:\\users\\nawin\\appdata\\local\\programs\\python\\python39\\DLLs',
'c:\\users\\nawin\\appdata\\local\\programs\\python\\python39\\lib',
'c:\\users\\nawin\\appdata\\local\\programs\\python\\python39',
'C:\\Users\\nawin\\.virtualenvs\\djangoprojects-rmJaG_g2',
'C:\\Users\\nawin\\.virtualenvs\\djangoprojects-rmJaG_g2\\lib\\site-packages']
Server time: Mon, 02 Aug 2021 16:07:39 +0000```
it throwing me error
Use the save method of your model?
Show your html
just for understanding how python works without packages ๐
Hey @rocky ferry!
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:
@versed python https://paste.pythondiscord.com/ejozimijix.php-template
Line 457 has an error
yeah
static '#' doesn't resolve to anything so Django raises an error
Either remove it or use a valid url
?
What part didn't you understand?
i think i missed a space
but my friend
no error but it is not loading background image
my background image is not loading
and i got this
come to a voice channel
ok
This is a question that calls on a lot of the subjective. That said, here's one opinion. I like the colours and layout. It's following the F-method quite nicely. Overall, it's solid. If this is a new launch perhaps invite feedback from testers on readability? One suggestion does come to mind though...
One suggestion that comes to mind is the navbar. This may be a personal thing, but I would move the logo on the navbar to be aligned with the text below, and I'd move the buttons so the signup button is right aligned with the text below. I either go with that, or place the navbar links to the left/right as I have in this layout.
I need to set up an ultra basic, stoppable server in its own thread
For someone reason I'm having trouble finding a decent (and modern) example.
Sorry to butt in @ionic raft
waits in corner
No apologies needed... Have you played with Flask at all?
I agree. Thanks, I didn't notice that with the navbar but I like the idea, I appreciate it.
I'm having second thoughts about the dark-blue card below the google map. So I'll play around with the colors and see how it goes.
I'm hesitant to have to crack open a whole new framework ๐ I'll do what I have to though. Back in python2 there was SimpleHTTPServer and it suited my needs, seems to have fallen out of favor now though
You're welcome. I like vertical alignment. It's provided clarity in much of my design. The alignment of the navbar to the elements below will sharpen it IMHO.
As for the dark blue box, that's a good observation too. It does dominate. You want to emphasize it, but not overwhelm the page. Now that I look at it, it does have the benefit of drawing intention of the page, but imbalances the page a little. Perhaps a dark blue border rather than the block?
Just the site itself. No GET or POST requests, as the JS runtime is connected to Python by other means (kinda convoluted)
So I just need to be able to load the site without CORS issues
The question of what you're serving is essential. I suggested Flask because it is a very simple framework that can let you stand simple sites up very quickly. However, if you've got more complex requirements those are important to consider.
ngl would be simplest to just use Nginx in a docker container to quickly serve some stuff, otherwise if you want really quick and dirty, the flask development server will serve crap from /static
Well then let me describe my problem and let you guys, the Jedi, point me in the right direction. I'm working on building a graphics library that leverages two rendering tools, wxPython (widget based) and cefPython (an HTMLRenderer)
CefPython is a set of python bindings around the C/C++ code in Google Chrome's open sourced equivalent
So you can launch an HTML renderer and do pretty much anything you want with it. Just like any normal browser though โ cors restrictions. Which means loading resources/assets requires a server. Cefpython exposes the Javascript runtime to Python, I assume, by way of a shared C runtime under the hood, though it could be a socket. So I don't really need anything complex for the passing of data, just the serving of resources
Its looking as though Flask is going to be the simple approach ๐
looking better already. I made a lot of design changes and spend so much time tweaking things... but overall through all the hours of doing so, I've found the simpler things look and the less I think about it, it becomes better...
originally it looked something like this
so there's a huge difference there
Nicely done
The border for the bottom-right reviews frame is MUCH better. ๐
I like the rounded edges too.
I did like those colored rounded-rects though
What about the "Write a Review" button as the same dark blue as the navbar? Black seems a little off from the colour theme....either that, or have a call to action colour that is more active but in the theme?
What about the same colour as the Sign In button?
I tend to go for a common CTA colour for buttons
And I would like to see the navbar elements aligned with the page elements if you're up for it. Seeing it will help validate
How to convert images into svg first?
use some package to do it
I hear you about hours into design. In looking at my own design screenshot I realized I needed to fix the imbalanced footer...I removed a style from the button classes...and simpler IS better ๐
Btw @opaque rivet any feedback on my overall base design are welcomed.
That imbalanced footer has been on my to do list. Funny how it got resolved in about 30 seconds ๐
Well, if anyone has anything to say about my server thing, just DM me
That's feels to be a scenario with a lot behind it. I've got a knowledge gap on a number of the pieces so don't feel qualified to directly answer. I am reminded though of the web app I'm building. But I started back-end with using Python views in Django to bring all the variables forward into the front end so that I can build the app for the user to manipulate them as visual objects in the front end. However, I'm still working my way into that skillset.
However, since you're connecting Python to the front end another way I'm definitely out of my depth to answer. Good luck tho. Someone will pop by and offer insights I'm sure
for a simple python webserver, I would say Flask and with it being one of the more popular ones you'll have a lot of guides / materials to help you
yeah - haha! Recently I've been using a bit of Figma for the design process. It makes nice illustrations at times but I feel less like a fullstack developer and more like a designer using it, a crap one at that...
Thank you!
Just having trouble finding an example that runs in its own thread. But thanks!
Oh yes...that's better!
OK...this is uber-anal as an observation...But what about the spacing between the border and Reviews heading. What if the spacing top was equidistant to the spacing left align? Also, what about the same font size for accom address and the "There are no ratings yet."?
Oh my goodness...My mind keeps bringing stuff up. What about the same spacing between the map/reviews box, and the navbar/map widget?
Anyways...that's more than enough poking around on that. Great work @opaque rivet I think you're onto something very solid with both the idea and the prototype! Best of luck
thanks for the tips. I really appreciate it, and we definitely improved it and I learnt some stuff. My design eye isn't the best but it's great having others sharing their opinions... I've tried to equalize out the spacings between the cards but there's still more stuff to do:
You're very welcome! The equidistant layout for the Reviews heading is more balanced.
I'm not keen on the placement of "Files". I'd prefer that within the navbar, likely a sub menu. That may be a typo tho.
I really like that design!
oh yea, that was just my sidebar of my OS when screenshotting
thanks guys!
will continue iterating the design now that I'm on the right path, design brain is fried. time to fullstack
That figures...yes, that design is a great start. Definitely on the right path! Best of luck! And yes, I'm turning a fullstack corner too. Finished a key foundation piece and now into app 2/7! This is exciting isn't it! My first web app project!
very nice. I'm very similar. Are you going for a career in fullstack / software engineering?
Actually, I'm a business consultant of 20+ years, and visual developer in the SharePoint/Nintex Workflow stack for over 12. Thing is that stack while powerful is a closed garden and expensive to get into. I had an idea to automate the process improvement/collaboration tools I train clients on. So LanesFlow was born. This web application is actually an idea to launch a company around. So, April 15, 2021 I picked Python, and here I am 3.5 months later. Started with Flask in June to get foundation, and then shifted to Django in July. On Saturday I just worked out how to take user form input, combine with queried DB control data, and create records. A big moment. I'm starting to see this idea as being VERY feasible to get the prototype working for.
What about you? You preparing for a fullstack career? You've got a solid design eye IMHO.
Discoveries abound. This discovery opened up LanesFlow to consulting agencies as well as client organizations. Consulting Agency subscribers can have multiple orgs, and associated teams, and self-serve add/edit/remove their orgs and teams. This sets the stage for the 7 LanesFlow phase 1 apps. It turns out that along the way I stumbled across ideas that expand the potential target market for LanesFlow...
giving me inspiration for some reason 
Here's the result of my most recent discovery...the consulting agency Org dashboard
oh wow, impressive! Very accomplished. You definitely won't go wrong with Django. I also started with Flask and went to Django and more recently have been trying to train myself on the frontend frameworks (next.js / React) for the sole reason because it's got demand in the job market. I've only got about 2 projects, one is similar to OneNote (but a webapp), and one is for NASDAQ equity data and I've been getting into ML which I want to attach as a microservice module one day for some quantitative trading, but that's a large way away... After this project I'm designing (which is for rating university accommodations) I'll start applying to jobs.
What is the use for me
Of learning rest Framework
I dont want to make APIs ;_;
But i want to make Backend of Mobile Applications by django i want to integrate React Frontend by django
Solid start! You're building great projects for your portfolio; showing an eye for value, design, and functionality.
We are following a similar path. I'm taking my time with Django and getting these data/application layer built in Django before diving into JS and front-end frameworks. I've got a diagramming app to build as the final piece in phase 1.
Anyone has good site to learn php?
do Django have more features than flask? or what's the difference? (i'm new)
good path imo. For a diagram app where there's a lot of user interactivity, I would definitely recommend React - usage with it has been simple and there's great animation / drag n drop libraries with it.
Your frontend will have no way of communicating with your django backend without an API, same with mobile applications.
That's a great question. Yes, Django is a framework suitable for complex web apps. It has admin/authorization/users/groups and tools like Class Based Views built in. It's more complex to get going, BUT compared to Flask it has more meat on the bone. Flask is excellent for a simple site. But if you're going to have lots of functionality and want solid security, Django is a great option.
For example, when I learned how to write Class Based Views to update/delete records, I could pull in UserPassesTestMixin to ensure ONLY the right person can change or delete the record. Django takes care of much of the security (and in this case throws a 403 forbidden page if the user is trying to sneak around).
OMG...great to hear! Yes, I've head about React! the diagramming language I use has 7 shapes...and is quite simple. Withj the back end work I'll have all the variables I need to bring past-saved maps forward. Also, planning on a form-wizard to offer a simple map build for noobs. Along with an open canvas.
Umm how can i learn it
Plz plz don't say it's docs they are not complete any course or video lecture if so better
Btw Learned to make CRUD and that serailizers part
hmm ig i'll start learning it 
My recommendation...start here: https://www.youtube.com/watch?v=UmljXZIypDc&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p
In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic application running in our browser. Let's get started...
The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Django_Blog
Flask Tutorials to cr...
But in the crud the frontend was automatic by django rest Framework
Thanks
Serializers and the API classes from DRF have been enough for my usage. To learn, videos (probably). I tried learning from docs solely, but I would not say they are great. For me, I learn off blogs.
Ohh
What was the need for me to learn django so hard when i have to use Rest Framwork later for other stuff
RIP aryan @dusk portal
Corey will give you a solid start. At some point though, you'll have to step from following a tutorial to working out what you want to do. That brave step is the where the learning REALLY starts. Good luck!
because it's a stepping stone. just wait till you get to django channels then you'll want to rip your hair out
Agreed!
There is so much potential to Django. It's an astonishingly powerful framework. AND learning how to really use it can be challenging. However, it is so popular that there are many, many resources to draw from out there. Plus, if you're looking at a career in fullstack web dev, Django appears to be a serious player in a busy world.
I am creating Google form like web site and answer model is fine or it's better to create 4 column for every answer
What are the FastAPI advantages in comparison with AioHttp?
Is Flask easy to learn
Yes watch corey tutorial in youtube
i am getting this error every single time. I am trying to make custom user model and it worked fine for me in django 2.2 but in django 3.2 its not working. I am entering all the details correctly so no password error from my side.
Here is my models.py :
https://pastebin.com/3rq0bkbd
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.
did you figure this out?
im having the exact same issue rn and i cannot for the life of me figure it out
Created a superuser?
Also, if it's a regular user, make sure is_active is true for that user.
yup. successfully created superuser and its still showing wrong passowrd.
default user model works fine but custom user model giving this error.
Did you create a superuser before changing to a custom user model?
All the docs I've read about setting a custom user model state to make sure that you do it before you do anything else. So you could try dropping the DB and migrating the customuser before making a superuser.
i deleted the table. ran migrations and created superuser yet problem remains same.
i tried every possible solution but nothing seems to work.
tomorrow i'll try same steps with django 2.2
Hmm, something is probably not registering the user correctly, or ... maybe something in your settings but I doubt that.
I know one time I could not login (but without an error) due to missing authentication middleware.
i checked the entry in database and everything is fine there.
are you logging in correctly with username or email? whichever you have it set to?
and obviously making sure it's case sensitive.
yup 100% accurate.
actually many users facing this issue. i saw on stack overflow but did't get any working fix.
i have to use default django user model because of this and its really irritating

Well, I use Django 3 and never had that issue.
So something isn't working correctly.

Have you deleted the whole thing and just started over, still with the same issue?
yup still same
oh wait
AUTHENTICATION_BACKENDS = (
# Needed to login by custom User model, regardless of allauth
"django.contrib.auth.backends.ModelBackend",
# `allauth` specific authentication methods, such as login by e-mail
"allauth.account.auth_backends.AuthenticationBackend",
)
i didn't add this
maybe because of this?
ahh still same issue
Are you using allauth?
what if you put allauth first instead of second?
The order sometimes matters.
nah not using allauth but use this insted
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
still not working
how would I send information from a form from one html page to another?
Send the form data to the backend, and return data/context on the return aspect of that function.
That make sense?
wherever you handle your form post on the backend, handle the data however you want and then return render the new page with the data that was passed in.
If you are positive that you are using the right credentials, then something is wrong with your authentication, and if you didn't mess with it, then it's usually just a settings issue. I would really just scrap it and start over unless you're saying you did that and it still happens on a brand new Django app.
If you used the django superuser command, then it should be working normally right out of the box.
how would i do that in, say, js?
ok i'll try one more time with creating brand new project
Send the data to your django/flask server with ajax (through whatever URL goes to the proper function).
Good luck
what if i dont have a server?
how are you serving your site then?
is it just me or is that with FastAPI, when i return a redirect response from a post request it sends a post request to redirected route?
its just through the html files for now
Do you have a backend at all?
no...I guess
And what are you trying to do based on this form data?
send it to my other html file
JS would probably be the best way to do that if you don't have a server.
so it would be something like i have a form on file a and then i send the data inputted into that form to a list in file b
You probably want to read up on how to render to the DOM with JavaScript
But you won't be able to store the data without a backend (that could be Node.js, Python, or something else)
oh ok
how would i do that?
Here's a quick article on rendering basic content to the DOM https://gomakethings.com/rendering-content-with-vanilla-javascript/
Oh I assumed you have a backend since this is a python server.
alright thanks for your help
skip to were im currently at
with this here is the response - is there a way to stop the post request from being sent?
I already tried a 308 status code
you can't redirect a POST request
at least not normally
I mean all im doing is submitting a form and redirecting to seperate page
but when i redirect it re-submits the post request again
should i use formaction?
ye
that only changes where to send the request
ah
you could use a get request
or a click listener on a button that redirects when the form is submitted
sounds good
Are you automating the use of omegle? That sounds like something that would go against their TOS: https://www.omegle.com/static/terms.html#:~:text=use any robots%2C spider%2C crawler%2C scraper or other automated means or processes to access%2C collect data or other content from or otherwise interact with the Services for any purpose%3B making it against the rules here for us to provide help
Any luck?
I'm really curious if you figure this one out.
still typing ๐
Oh okay okay ๐
Hello. I want to first ask if there's a more streamlined community for dealing with webscraping, I don't mind asking questions here but I would like to know if theres communities dedicated to this. I use stuff like pandas on work so it would be to my gain being around people that also use that stuff.
As for my question, I been scraping stuff lately with BeautifulSoup and formatting them with pandas. The biggest problem I have currently is when it comes to inputs inside <td>'s and special characters inside <th>'s which doesn't give a good result.
Pandas read_html function has a great parameters called "converter", which allows me to just give it a function that will format all values on that row. Unfortunately it just takes the most inside value instead of the whole HTML tag. so that doesn't work.
So is there a proper way to:
- unidecode, .lower(), etc <th> tags
- get all of the content inside an td tag with panda, including html tags. Or a good way to "untag" a tag (removing the < and > from the tag). I could iterate through all the <td>'s with beautiful soup and untag the tags, but wouldn't that me require iterating through the tables 2 times (once with BS4 and again with pandas)? feels less performatic
from http.server import HTTPServer as Server, BaseHTTPRequestHandler as ReqHandler
class echoHandler(ReqHandler):
def do_GET(self):
self.send_response(400)
self.send_header('Content-Type','text/html')
self.end_headers()
self.wfile.write(self.path.encode())
def main():
PORT = 80
sv = Server(('127.0.0.1',PORT),echoHandler)
print(f'Server Running on Port ${PORT}')
sv.serve_forever()
if __name__ == '__main__':
main()
Exception occurred during processing of request from ('127.0.0.1', 2971)
Traceback (most recent call last):
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\socketserver.py", line 316, in _handle_request_noblock
self.process_request(request, client_address)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\socketserver.py", line 347, in process_request
self.finish_request(request, client_address)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\socketserver.py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\socketserver.py", line 747, in init
self.handle()
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\http\server.py", line 427, in handle
self.handle_one_request()
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\http\server.py", line 415, in handle_one_request
method()
File "D:\Python\Practice\app.py", line 8, in do_GET
self.wfile.write(self.path.encode())
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\socketserver.py", line 826, in write
self._sock.sendall(b)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
----------------------------------------```
the Code & the Error
Any Guesses ?
Evening everyone. I am looking for a suggestion on the best front-end for a Django REST API. It will be a relatively simple front end to include a search bar, item status, and form entry for date/times. Currently, my research is leading me to React or React Native. Any suggestions on which front-end would be best to learn?
If your app is extremely simple, you can use vanilla JS. If you didn't have any previous experience with frontend frameworks, give Svelte a try: https://svelte.dev/tutorial/basics
I'm hearing good things about React. Going to be looking into it for a diagramming app I need to do. In the meantime, here's the first app with links to other profile relevant info for the web application I'm building...
As of today, LanesFlow is 3,657 lines of Python, 2,298 lines of html, 546 lines of css for 6,501 lines of code, with a total of 177 files in the Django project. These things do grow, and I am having a blast. Django is AMAZING!
Hey folks.
I'm a C++ Audio developer with some server php experience.
Has anyone here made an app for GitHub or interacted with their API?
This is new territory for me, and all of the tutorials on Github about using Webhooks or Writing Github Apps assume that the reader of the tutorial knows what all of those terms mean.
Main questions:
- should I be using a VM to get my feet wet with Ngrok for the purpose of learning about Webhooks and payloads?
- I have a VPS via my current host. Once I get through these tutorials that show how to set everything up to develop using LocalHost, what do I need to do so that Github will send webhook payloads to my VPS?
I'm currently doing some Slack - Github - Gumroad automation via Zapier (running some python snippets when events are triggered), but i've reached the point where Zapier doesn't have enough functionality built-in, and i need to write my own stuff from scratch.
trying right now. just woke up.
brooo. it worked. all i did is start new project and first i make user model and it worked 

In oauth2 python django django-allauth
I'm trying to use a single central subdomain for oauth and the other domains are other tenants, you can think them as like separate dbs if that's more helpful to you
I'm trying to authenticate the users in customer1.localhost from auth.localhost
My callback url in the oauth2 config for, say, google is auth.localhost/callback
And google calls auth.localhost/callback?token=token
And I thought redirecting this to customer1.localhost/callback?token=token would work the same
But it doesn't, and gives me "Bad Request" on google's part
Feel free to ping me
should my views for custom error handling templates sit in the main app where i have settings.py asgi wsgi and such ?
hi im trying to create a telegram bot with python which fetches a random cat fact using API. currently all the commands work except /cat, could sb help to see why thanks!
TOKEN = "removing it due to safety"
import logging
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import os
PORT = int(os.environ.get('PORT', 5000))
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
"""Send a message when the command /start is issued."""
update.message.reply_text('Yo!')
def help(update, context):
"""Send a message when the command /help is issued."""
update.message.reply_text('Help!')
def cat(update, context):
update.bot.reply_text(chat_id=update.effective_chat.id, text=get_cat_fact())
def echo(update, context):
"""Echo the user message."""
update.message.reply_text(update.message.text)
def error(update, context):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, context.error)
def main():
"""Start the bot."""
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater(TOKEN, use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("cat", cat))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, echo))```
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_webhook(listen="0.0.0.0",
port=int(PORT),
url_path=TOKEN)
updater.bot.setWebhook('https://removing_name_for_safety_reason.herokuapp.com/' + TOKEN)
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()```
do i need to learn frontend before learning django?
Knowing the basics of html css and Javascript should be enough
ok
I have an issue with FastAPI, when i return a redirect with headers - the headers dont seem to be passed through
return RedirectResponse('/login', headers={'X-Rejected': "true"})
Headers recieved
['host', 'connection', 'upgrade-insecure-requests', 'user-agent', 'accept', 'sec-fetch-site', 'sec-fetch-mode', 'sec-fetch-user', 'sec-fetch-dest', 'sec-ch-ua', 'sec-ch-ua-mobile', 'accept-encoding', 'accept-language']
Basic html should be enough to get started
You can learn css/js later
i finished html course but i've a problem with css 
Nice
css is the hard part lol (imo)
I'm getting an error while trying to run my django project "Cannot use ImageField because Pillow is not installed", but pillow is installed ๐ฆ
Did you install pillow in the same environment as your django project?
yes
which channel should i learn django tech with tim or corey schafer? corey's vids are lil bit old is it not outdated?
Does any have experience authenticate the api using certificate(pfx) ?
someone suggested me corey
when did you started learning?
is it not too outdated?
yesterday ๐
idk maybe its not
i see thank you
Does any have experience authenticate the api using certificate(pfx) ?
Can anyone tell me why my lib folder is Missing on my Django project? I tried looking this up on google but found literally nothing helpful
what you guys think about sanic over django ?
๐ฉ
maybe the question you should ask yourself is where is it installed
I used Corey's Django video series to kick start my web application off. I also took the time to get through css, which is an interesting language. However, css is all about styling. So if you want function and form you'll need css. However, a lack of css doesn't stop you from building. It just helps with form. However, form without function is pointless.
Corey's videos are not outdated. He's got solid practices and his teaching style is excellent. 3 years old is missing some more modern stuff. He's using Bootstrap 4 when 5 is now out. Django version is a bit older, but not cripplingly so.
It is installed and virtual env is turned on
I installed it with my django files
run pip freeze in your virtual environment and let me know what you see
When using uWSGI should I have a .sock file, or is it the same as .ini?
I see pillow, pipenv, typing, virtualenvโฆ.
django there?
It will be in a couple of seconds ๐
alright then
Same thing
what do you mean same thing?
Same error, pillow not installed
the django you're running is obviously not connected to that virtual environment which is why you are getting that error
if you want it to work correctly, you need to run it from the virtual environment
I did
if it's giving the error it means one thing
Yees?
your pillow is installed in another environment
it will not give you a not installed error if both are in the same environment
etc
I tried reinstalling pillow
it won't make a difference if they are not in the same environment bro
what i suggest is you create a new environment and copy over your django source files and reinstall everything you need
Alright Iโll try, thanks
Hey there, could I get some help in #help-kiwi with nginx and uWSGI please :D
thanks for all the help
My pleasure!

Anyone?
What do you mean with missing? How did you create the project? Did you have a lib folder before?
It's not there. I don't know if i missed a step when setting up my Django project
I didn't have it before
If you're not losing much data/work, maybe just start the django project from scratch.
Can someone help me push my code to heroku because im getting a error saying
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to
Im using Django btw
( please ping me if u respond)
Hello, I'm using a selenium webdriver to test a django app. I am developing on an ubuntu-server vm with no gui via ssh. Is there a way to have the remote webdriver forward the browser content to my host machine?
An app for github? Wdym
You mean like their discord integration ?
this is a php api for github: https://github.com/FlexyProject/GitHubAPI
What field should I use when I want user to type their card number and then it processes through stripe?
Password field, or just a normal charfield?
Probably <input type="___" autocomplete="cc-number">
I forget what the input type would be, you can add that
Normal text field I think
hmm... I might need to add all the form fields manually, but thanks for the great answer
There are all of these really great cc values for the autocomplete attributed
That attribute (autocomplete) also works on the <textarea>, <select>, and <form> elements
What site did you find those?
thank you
helps alot
I haven't even thought about autocomplete
That's very important thing to add to the ux
hey somebody know a good way of making a http server that performs backend tasks
because i am pretty new to networking and i want to make a little website where users can do stuff, that gets handeled by the http server
pls ping me
Is there a reason to not use WhiteNoise?
tell me more...
No I was asking my own question
It wasn't
ok
Anyway, to answer your question, your python options are django and flask
In general, if you need databases, use django. If not, use flask. Flask is really light weight.
The django official tutorial is great
n*
Or, Corey Schafer has a video series on django
Does anyone know how to use heroku?
Is python avaible to do web development without Django,Flash or anything else. I just want to build one with Python thats it.
Not really. You need a web server to serve the html.
That's what Django/Flask does.
But you code everything in Python.
So it's basically just Python.
You just need to know some basic html/css for the pages themselves.
I know html just the simple stuff. Like the headings, bolding, and just the writing area.
Do i got to download flash?
ofc you need some modules for web dev
you can't make it with built-ins only
(Django web dev.)
Can someone help me push my python code to heroku? I need help with this because it seems I am missing a step because when I use the cmd to push the code I am getting an error that looks like this
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to
Please ping me if u will help
python is not made for just that
Ofc I would import stuff. Is flash/django in the import area if it is im dumb
How hard is to integrate turtle with a Flask website?
Let's say I wish to take some user input via text boxes in the browser and show a turtle drawing?
Has anyone done it?
if you a beginner i recommend reading django for beginners because its a great book and im even reading it rn tho i ran into a error lol
book~ 
im googling it rn
the book will teach you a lot about web development and u dont even need to stick to python after u read it u can learn another language (which im am prob gunna do, ill switch to CSS, javascript, or what ever one most web developers use)
Django for Beginners by William S. Vincent
ok
Tho in that book i ran into a error at the heroku deployment part and now idk how to continue forwards cuz I cant launch my code to the public :/
now I gotta wait till someone who knows how to use heroku responds to my question lol
google it
I have tried
claim help channel
youtube, google, reddit, stock overflow ive tried them all

holy shoot dude
if this works
tysm cuz ive been looking for a answer for 2 or 3 days now
dang thanks for the help but it didnt work
??
lol
You can't run lsof?
Unless they have a way to do it, you need the id of the app that's running.
This a linux server?
So normally you lsof -i :port
then kill -9 id
but you need the id from the lsof part
port is the port your app is running on
Hello
<!DOCTYPE html>
<html>
<head>
<title>Panel</title>
<link rel="stylesheet" type="text/css" href="css/changelogstyle.css">
</head>
<body>
<header>
<div class="main">
<div class="logo">
<img src="logo.png">
<ul>
<li><a href="index.htm">Home</a></li>
<li class="active"><a href="ChangeLogs.htm">ChangeLogs</a></li>
<li><a href="#">Discord</a></li>
<li><a href="#">Stats</a></li>
</ul>
</div>
<div>
<h1>Version 1.0.0 - 3th april 2021:</h>
<ul style="list-style-type:disc;">
<li>Added gang war mode</li>
<li>Added deathmatch areas</li>
<li>Added copchase/cnr mode [under developent]</li>
<li>Added Duel system</li>
</ul>
</div>
</header>
</body>
</html>
There is two <ul> </ul>
How can i put two lists in 1 page?
Looks like you did it.
i want to give each list a different font
in css
How can i do it?
Why it didn't appear as list
<ul class ="left">
<li class="left"><b>Added gang war mode<b></li>
<li class="left"><b>Added deathmatch areas<b></li>
<li class="left"><b>Added copchase/cnr mode [under developent]<b></li>
<li class="left"><b>Added Duel system<b></li>
</ul>
@dense slate ?
-_-
I have a Flask server that essentially streams whatever is my usb camera looking at
But I have a problem - it seems to need to access camera for each machine opening the site
So, for example, if 3 of my friends wanted to check the camera at the same time - I would kind of need 3 cameras
I am interested if it's possible to somehow use one camera and share that stream on the page
Not actually access the camera each time someone is looking
bruh does no one use heroku?
it's very popular! i think its mainly because heroku makes deploying easy
Anyone DM who have good experience with flask thanks 
You're better off just asking the question in this chat
well am gonna go with coreys tutorial wish me luck hehe ๐
the reason is because I need a lot of help lol
exactly... would you rather get help off 1 person or many more?
would you like to help then
@opaque rivet hmm?
maybe I can, but it's 4am so not sure. Just post the question and you'll have more luck than asking to ask someone a question...
https://replit.com/@Team3AM/InclusiveAlgorithmPrototype?v=1 I am trying to migrate this whole algorithm to a web app via flask @opaque rivet
Ok. So what is the question? Have you learnt Flask?
mhm I am currently
Good luck! Although I don't think you'll need it. He is great and you'll get a lot from it. ๐
Hello lovely people ๐
Any tutorial or docs on how to display turtle ๐ข drawings on a web page? Incorporating it in my flask web app?
idts
even i searched for pygame once
but it doesn't work
Shit
Two simple ways:
Within your website, you could embed your python turtle code using Trinket, https://trinket.io/turtle, click on the Share button and select Embed option. Copy and paste the <iframe..> into your website. Trinket offers other libraries like pygame but at a cost.
For something more advance, explore Skulpt: skulpt.org. You can also embed your code, but if you want to learn how is done, check their repo and the JavaScript code behind it: https://github.com/skulpt/skulpt.
hello i just started learning django rest framework and made some api's
now i wanted to integrate my django and react (reactify django )
so i saw video of dennis ivy but
he was not using the Func based view
from django.urls import path
from django.views.generic import TemplateView
urlpatterns = [
path('',TemplateView.as_view(template_name='index.html'))
]
he used generic views, so i did too and yes it was working but how i can render it in my function
and i want to make a view for it how can i do(ig ofc we're gonna use django rest framework)
TemplateView wont work as a rest api. What are you trying to do?
Till now i haven't added rest Framework @versed python
I just want to Reactify my django
Hey, thanks. I just need to interact with their API and learn to use it so I can communicate between Github and Slack, without using the Zapier integration (because it is lacking)
There's no such thing as reactify Django. They are separate libraries solving separate tasks. You'll have to use some way to make react communicate with Django. Rest is the most common method. Graphql, soap, websockets are others.
Ohh i should not relate rest framework and Reactifying django as a same thing got it
But with simple django i can't use React right?
So we make APIs by rest Framework
And get things working and done
@versed python
@opaque rivet where r u master
You technically can but its quite difficult
Umm
I have Learned Django ( Till a good lvl)
And rest Framework fundamentals
Now wanted to Reactify Django
You can make a api using django for your react application
Hey, I keep getting *144 connect() to unix:/home/dan/flaskapp/flaskapp.sock failed (13: Permission denied) while connecting to upstream, whenever I try to connect to my website using the domain name
The first one is checking if the method of the request is post
not sure about the second one, i have not used flask
So, this is going to involve JS, but it mostly involves CORs and HTTP stuff
Are there any headers I could put into a GET request that would make me able to get static content from a neocities.org subdomain (so thata I don't have to host that content on my VPS web server). It's a CORS policy block. I know that sometimes you can set the right headers to get things to work, but I figure to some extent, it has somewhat to do with how neocities.org has configured their server as well.
If it were possible... what would I do... The docs are pretty confusing. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
The only allowed values for the Content-Type header are:
application/x-www-form-urlencoded
multipart/form-data
text/plain
so... what if I tried....
const fetchUrl = (url) => {
const reqHeaders = {
headers: {
"Content-Type": "application/x-www-form-urlencoded" // not sure what this means tho.
}
}
axios.get(url, reqHeaders)
.then(res => {
console.log(res.data)
setUrl(res.data);
setResValid(true)
})
.catch(err => {
console.log(err)
setUrl(props.url);
setResValid(false)
})
}
and lets assume that the content in question is a large (704kb) animated .gif file that I should just not use as is probably lol
Hi
I've a object
with its serializer
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = models.Comment
fields = [
"id",
"messageId",
"time",
"message",
"username"
]
I get user like this, how do I get the username in the serializer itself, "user" gives me the id - "username" errors out
@dusk portal API endpoint should return JSON data, not templates
I was just watching Dennis Ivy's tutorial to integrate Django with my react app
He was using TemplateView to render out react frontend
Can u tell me how can i use fun based view to get my frontend
Btw i got idea of other things like when we make any change in any react code so we have to run npx run build and those other things
@opaque rivet
Tell me plz + give me any good source to learn React and to work with rest_framework and all
You need to make a api using drf and you need to send requests to it from your react front end
Anyone can help me with django?
If you're using create-react-app, you're going to make a single page application, so all of your components are rendered conditionally on a single .html page (usually index.html in the public folder iirc).
You need one view from your django backend to serve index.html with all of the bundled JS within it. So once a user visits your root URL, your django backend returns index.html and then all of the interactivity is handled by React frontend. From there all API calls should return JSON data.
You ask this question a lot... 1. Docs 2. Blogs / Courses 3. Videos
agent = models.ForeignKey("Agent", on_delete=models.CASCADE, null=True)
I've set it to null=True but still it makes me set the agent..
I'm following JustDjango CRM tutorial
did you makemigrations and migrate?
hmm, try setting blank=True too.
k
still didnt work ๐ข
Migrations for 'leads':
leads\migrations\0001_initial.py
- Create model User
- Create model Agent
- Create model Lead
(env) PS D:\Django-CRM> py manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, leads, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0001_initial... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying sessions.0001_initial... OK```
hmm, blank=True should allow forms to submit with an empty field. Are you using a form you created?
Nope it aint forms its using admin site
@dusk portal please contact
It's weird that's the case. Possibly you can make a custom form and attach it to django-admin instead of using their one.
aw man im just a beginner
how can i add 1 field to all forms existing using a Mixin
๐
is there any way to do so ?
Custom form:
# app/forms.py
class CustomForm(forms.ModelForm):
class Meta:
model = your_model_here
fields = "__all__"
Admin:
# app/admin.py
class CustomFormAdminModel(model.ModelAdmin):
form = CustomForm
admin.site.register(CustomFormAdminModel, your_model_here)
Got it
k will see ๐
It worked
I did blank=true and null=true for another var in agent class and the agent model
@opaque rivet https://stackoverflow.com/questions/8609192/what-is-the-difference-between-null-true-and-blank-true-in-django This what I used tagged you so it might help you ig
I know their differences, what other field did you set blank=True for?
just wondering.
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
age = models.IntegerField(default=0)
agent = models.ForeignKey("Agent", on_delete=models.CASCADE, null=True, blank=True)
def ___str__(self):
return f"{self.first_name}"
class Agent(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
def ___str__(self):
return self.user.username```
also while you see that, my str method aint workin the 1st one ๐
so you added blank=True to this?
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
Doesn't make sense why that fixed it.
I would highly appreciate if you could check out this (probably simple) question regarding Flask. Thank you very much!
https://stackoverflow.com/questions/68647356/make-stream-accessible-to-multiple-machines
uh nvm idk what is happening
hello!!!
my django connection times out after certain minutes
i'd like it to keep going indefinitely. How can I do this?
I tried to find answers on google but sadly couldnt find any
@prisma heart if you remove null=True and blank=True from your user field, does the issue re-appear?
suggest me some proj that i should make to enhance my learning of the rest framework and React
Hello, I am once again asking for your FastAPI help:
I am trying to serialize some models in an api, but the values the api is returning seem to be ignoring my response_model. Could anyone point me in the right direction on how to get this working?
# code
class Task(TaskBase):
id: int
owner_id = int
class Config:
orm_mode = True
@app.get("/tasks/", response_model=list[Task])
def read_tasks(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
tasks = crud.get_tasks(db, skip=skip, limit=limit)
return tasks
// api response
[
{
"title": "My test task1",
"id": 1
}
]
update: I big derped and try to type hint when setting a kwarg value
BUT it is still not working, sadly.
I always tell people to make what they would use themselves
It shouldn't do that by default, have you checked the output for errors?
@surreal thicket Won't your solution be a single shared instance across all the users? What if I want each user to have their own separate persisting session?
i didn't know your use case. in that case you can use flask.session https://flask.palletsprojects.com/en/2.0.x/api/#flask.session
So basically, I've already implemented all of the logic around consuming JWTs, and all of the business logic for my application in the upstream backend server. I should not need to replicate 99% of the business logic I've already written on the server on the client.
I want the frontend server (the project I'm describing here) to just have a couple of very basic view templates that are populated by a request made to the API server. But, a persistant session is required cases where the user been logged in.
Basically the frontend server should be a very basic thin client that acts as a graphical frontend to JSON requests, and automatically manages its sessions per use with the API server (including token refreshing and logging in)
client - frontend server - backend server
you already have auth and business logic set up on the backend server, and you want to "pass through" login info from the client to the backend server?
I guess I could return the token to the user in their cookies, and they provide me with the JWT every time? And we merely use that with this request.Session object (drop-in and update it every time?), instead of supporting an individual client session object for every single request. I don't know the implications fo rthat
is the JWT stored in a cookie on the client side? maybe it's as simple as passing that cookie up to the backend
i am not a web dev expert by any means so this might be bad for X or Y or Z reason
you don't need the requests.Session unless you want to persist cookies across requests. sounds like an optimization rather than a requirement?
if the client were to communicate directly with the backend, how would they authenticate?
Yeah I'd sort of rather want to avoid sharing the JWT straight-up with the end user. Maybe the frontend could issue its own session tracking info.
Username/password combo
as in, http basic auth? or something else?
Oh, let me check
I'm not sure how you would get away with not sharing the JWT with the client.
How else do you send new requests to the server when auth is needed?
I think it's just HTTPBasicAuth
Theoretically, you could issue your own session token between the frontend and client, and basically only whitelist the frontend server for being able to communicate with the backend server. I just don't know the security implications of just sharing the JWT in the context of my whole application
Even with JWTs, you usually only whitelist the front-end.
Unless you're allowing oauth, I suppose.
Even then you can handle that on the backend I think.
I want to avoid Oauth
Where do I put the main home page views and templates? Do I need to create a new app
Where can I use it?
There are scenarios where you are doing server-to-server (or microservice-to-microservice) communication in the backend and one service could generate a JWT token to send it to a different service for authorization purposes And other narrow places, such as reset password, where you can send a JWT token as a one-time short-lived token to verify the userโs email.
My instincts are basically saying something like this ^
yeah, i was about to say, this actually sounds correct for your use case
but it does sound like the "frontend server" needs to maintain some kind of server-side session state still
so maybe you use the flask session business for that purpose
then you store a JWT and a requests.Session instance in each flask user session, that you use to authenticate w/ the backend
My CTRL key wasn't working so I wasn't able to save anything so my code wasn't working, It just works if I use null=true and blank=true
see, that explains it.
yeah, me dum
yeah big brain nick
Okay yeah I was thinking along these lines too . So would each user also correspond to its own backend request session? Ie, a separate request object for each user?
I'm creating a Django website, Where do I put the main home page views and templates? Do I need to create a new app?
yeah that could be an easy way to do it. not sure if there are security implications
Additionaly, Flask has facilities for the front-end for dealing with various session vulns, like CSRF, so I if I decouple microservice-to-microservice JWTs from basic flask frontend tokens, I can leverage that stuff
yep exactly
also if you don't need to persist sessions or whatever you can probably just store session data in a dict
obviously that doesn't work if you have multiple containers or something like that
You can just keep the JWT token as an http-only cookie.
or wait no, you use the flask session object itself
what do you mean by that
That way you can access it but not modify it.
Um, not sure how to explain it. That's just kind of it. You can lookup how to set an http-only cookie on whatever platform you're using.
what do you mean by "http-only"?
ah, i see https://owasp.org/www-community/HttpOnly
i don't think that solves all the problems with JWTs in the articles i linked
What problem are you trying to solve?
me personally? none at the moment, but i just posted like 4 articles that say why you shouldn't use them for client authentication session tokens
actually 5
Right, I'm saying to use cookies, not sessions.
What if someone seizes the JWT token from the http-only header and replays it in their own unauth'd session with the frontend?
Oh it's a cookie
@viscid island The best solution for that is to have a short-timed token. Like 5-15min.
And refresh the token as needed.
I do have that. But you can do a lot of damage in 15 minutes
Yea, security isn't perfect.
These are just layers of security measures to minimize damage.
I think maybe I'll just use flask's managed session tokens with the user, to lookup the JWT used for the backend requests to the API server
Alright cool. Very helpful discussion @dense slate and @surreal thicket !
Would love to hear how you handle it in the end.
Going to be working on this exact problem the rest of today
Oh, btw, you can make the token like 5 min, or less even, and use the refresh token to renew it until the use logs out. @native tide
You can even have the token as 5s if you want.
Just more server requests, so balance it how you need.
My concern about JWT is that it isn't tied with the request itself, but an infinite number of uses within some time period. This is unlike how something like HTTPS or Axlotl works
conversations_about_security == 'always good'
I'm trying my best to leverage built in security features in Django (csrf_tokens, UserPassesTestMixin, built-in hash+SALT pw) but I feel like there is still more to know.
UserPassesTestMixin, LoginRequiredMixin and user.is_authenticated are some easy-to-implement gold though.
You can do Flask and Django projects without javascript right?
Yes, so long as you don't need front-end behaviour.
So far I have built my web application just with Django. I do plan on JS/React, but that's only for front end behaviour for a diagramming app. However, Django does all the server-side heavy lifting. If I wasn't building a diagramming app it could all be in Django.
If anything, there's something to be said for server-side processing over front-end processing. Based on my limited understanding, the more you keep server-side the more you leverage server processing power and the fewer security vectors you open up. That said, I am always learning and happy to be corrected. Even poor back-end security is poor security.
I'm making a simulation of payment gateway system as my final y project. Should I use socket programming or make a web app for it ?
Mostly. Or that depends. The way I see things are as follows: html gives me front-end structure, css gives me pretty/style, python gives me application + DB mgmt, and jinja gives me conditional formatting in the front-end. What JS brings is the ability to manage front-end behaviour. There are things that can be done front-end that are easily done back end. For example, I can use JS to calc the year and ensure the footer is the current year. But I can, and believe I should, do that in views.py.
Hmmm...a good question. I am not familiar with socket programming. But I am right in the middle of coding the Stripe processing app for my web app in Django.
That depends. Python/Django will let you process a web request server-side and send that up. However, you have to wait for another event (or use a Signal) to extend behaviour. What JS gives you is the ability to let the end-user trigger behaviours in the browser. For example, for the diagramming app I'm going to code, I want to render the base canvas, and then let the user drag drop shapes etc, and have the front end manage things like organizing/snapping those shapes. That's where JS is strong. Then, when they click Save, the back-end takes over.
I will also use the back end serve up forms as a wizard to build their first diagrams. This back end processing will then setup the render for the first app. JS will then let the user take over, and edit the diagram
I heard JS can do animations and stuff, basically execute scripts in the device
While django/flask are sorta limited in that matter?
Yo when you are making a website how do you know which folder is the root folder?
Nvm I'll make a web app. That way I can make an API for it too
Indeed. I've heard that too. However, remember that all that front-end processing is load on the browser. Heavy scripts are also data being sent out.
Django/Flask don't really do front-end dynamic behaviour. I can use Django to control what the visitor sees. For example, I can enforce if they're authenticated, or have a certain value in a table to determine if they see stuff. But if I want dynamic behaviour/interaction in between server requests I need JS
Good strategy. An API has its uses, but it is just a middle-man for data.
That depends on the framework. Django and Flask work differently in terms of file structure.
In Django the hierachy is flat, with the core project dir the name you gave the project. Each app has its own folder.
In Flask it's much more flat, simpler to understand, but gets less clear the more you add. Which is why Flask is good for the simple sites.
So the root folder is is the folder that you called your app? (for Django)
For example, this is entirely Django:
And there is much more going on to build that page than appears on the surface
yea but how can I know which folder is the root folder on vsc because It is saying i did not set up heroku on my root folder
I'd suggest going through a Django tutorial. I started with this one, and it's excellent: https://www.youtube.com/watch?v=UmljXZIypDc&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p
In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic application running in our browser. Let's get started...
The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Django_Blog
Flask Tutorials to cr...
I use PyCharm, and have only limited experience with VSC. Are you in the middle of deploying Heroku?
That tutorial is free...and is outstanding. A month later and I've made astonishing progress based on the foundation Corey gave me
Yea im trying to deploy it but it seems every time I fix a error another error appers
Hey all, anyone willing to help me navigate the utter chaos of nginx? It should be a simple server but I am getting 404's
I had a mixed experience with Heroku. I got a Flask app deployed before shifting to Django a month ago. However, I came away from the experience with a sense that while I got it working I'm going to want my own dedicated hosting. I'm going with Linode. But then I am building a business web app.
I really dont feel like switching the host rn cuz its starting to feel like I may have to restart a lot of this rn
I also found that my lack of experience in setting up a working virtual environment created project dependencies in the Flask app that compounded the issue. I literally ended up un-installing Python and restarting all over again. From that pt on I use virtual environments for every Python project. That way, all package dependencies are isolated and controllable.
I hear you. I'm not suggesting you change hosts. Heroku is free and will give you a hosting option. It's a bit of work to get there though sometimes.
There is always the option of GitHub pages too. They're free and will allow you to host a project if Heroku doesn't work out.
Yea it really is, I spend 3 days try to figure out how to fix a issue and today i finally fixed it only for another issue to appear, I might switch host but I kinda wanna stay using what the book uses so i dont end up messing things up
You know what though I may just restart the book :/
ima go take a break
I took over a day to fix my issues with Heroku. It also became apparent that with a free service you're on your own. This means lots of research in Stack OVerflow for the errors. In my case, I needed to get project dependencies worked out. But in the end the flask project did get out there...
https://lanesflow.herokuapp.com/
Has this app changed since I moved to Django. However, as a learning experience it taught me much!
LanesFlow is about a vision to make the complexity of collaboration clear, to empower teams in solving the puzzle of understanding how they work together and communicate, and how they can realize breakthrough improvements.
I can also see that Heroku has issues because I deployed it with a sqlite3 DB but it uses PostGres...and moves things around, so data doesn't stick.
Wow...have I ever built and changed much since that first month in Flask!
You know what, Ima restart the book and If I run into the same problem again then ill use the tutorial u used and try that out
Now I feel motivated thanks
Tho ima start after a break
I can really relate. Sometimes, stepping back is key. And going through a video tutorial may give you a different perspective and pace that builds on what you've already learned. Corey's teaching style really is excellent. Good luck!
ty
I am using Corey Schafer tutorial.
https://github.com/CoreyMSchafer/code_snippets/blob/master/Python/Flask_Blog/11-Blueprints/flaskblog/templates/home.html
In home.html, I am confused linking to the individual post. Do I need a for loop because it links every posts? Is this the correct line?
href="{{ url_for('posts.post', post_id=post.id) }}">{{ post.title }}
How can you access S3 Static files in a Django View?
what would be the best way to implement a code to join a group? through a charfield or through a uuid?
why?
Either one does the job. Just however you want to do it.
In favor of UUID, UUIDs can be automated to always be unique.
Well, I guess strings can too.
im using a mix of both atm, using a charfield while a uuid is generated for new object. you recommending the uuidfield?
is it better to use the uuid model field instead of the charfield?
If you're using uuids, yea sure. I don't know if it matters but you can use unique=True on a uuidfield to force unique ids
Plus it makes sure you don't get other values in there by accident by forcing the uuid type.
Like a mis-typed uuid.
can i specify string length with the uuid model field?
That I don't know.
damn
I know that uuid and uuid4 both work, so maybe it's set to accept all UUID object types.
Does anyone know if it's possible to do something like overflow-y: hidden on only the positive Y side?
what's the best way to persist something like shopping cart data?
where should I start !
Could you explain what you mean?
If you're using some frontend framework, they'll have a store management system. Vuex for vue, flux for react etc
Managing state manually would be pretty difficult
Cookies as a frameworkless approach to it
yea. that resets on refresh
exactly how would you use cookies here?
I'm having an issue with a Django app im working on. I have some models that have M2M relationships with others. I am trying to call manager methods on related models from another and its failing:
Details are here:
https://stackoverflow.com/questions/68652149/how-do-you-use-a-custom-model-manager-method-for-a-related-many-to-many-model-fi
If anyone could provide some assistance with helping me understand why I'm not able to get this method to work, I would appreciate it. Thanks!
thanks
Just make your data about client choices being in json compatible way
jsonify to string and put to cookie.
extract in reverse process if needed ;b
bro how can we use function based view while working while django + react (the django rest framework)
@inland oak
it's best to take advantage of class-based views when using drf because it can make organizing alot nicer, especially if ur using model viewsets which are awesome when building an api
ohh
thanks
i'll do that
from django.shortcuts import render
from .serializers import TodoSerializer
from rest_framework import viewsets
from .models import Todo
class TodoView(viewsets.ModelViewSet):
serializer_class = TodoSerializer
queryset = Todo.objects.all() ``` some uses this way
some uses this waypy from .models import Todo from rest_framework import generic class RoomView(generic.CreateAPIView): queryset=Todo.objects.all()
but while learning rest framework i was using @api_view and that things
in a function
@api_view(['DELETE'])
def taskdelete(request,question_id):
task=Task.objects.get(id=question_id).delete()
return Response(task.data)``` how can i create generic view for this
@wooden ruin
Django, API, REST, Generic views
Hi, my first time trying web scraping and I am using beautifulsoup for parsing. find_all method returns none can anyone help me with that?
html_text = requests.get(URL).text
soup = BeautifulSoup(htmltext,'lxml')
freq = soup.find('div', class= 'jss190')
print(freq)
I am trying to get the 50,004 value
hey i making a todo app using django
and i want to use django filters to shorten then description output
something like this
hello sfd dfsfs sd......
so i used truncatechars:9
but django is showing error
that truncatechars invalid filter
im using django templating engine
make sure those elements are there in the page source and are not generated by javascript
what is the difference between webdev in python and webdev in html css js
its like frontend and backend
html css js are used in frontend and python is used backend
how can I be sure of this ? And what can I do if it is generated by javascript? I have limited information about these topics.
you can check the page source (not in developer tools but right click the page and view source) to check if the element is there
it it's generated by javascript, you'll need to use selenium instead, that's a library that lets you control a browser from python
This is a screenshot from the page source. So the value that I am looking for is there. Do i still need selenium ?
give me the site link
let me check
I am unable to make authentication via POST request on a Django app (Nginx/uWSGI, Https) using the requests module in the client side.
The error is about Csrf token verification failure. (My different conf are here https://stackoverflow.com/questions/68651632/django-nginx-uwsgi-csrf-verification-failed)
Does anyone know where I could look to solve this issue?
i need some help with path in djnago
:ok_hand: applied mute to @rocky ferry until <t:1628160565:f> (9 minutes and 59 seconds) (reason: attachments rule: sent 7 attachments in 10s).
bruh
@rocky ferry it'll be easier to just post the output of tree (for us to be able to see your project structure) and one single code block having comments for which line of code you're pointing out in each file
!unmute @rocky ferry
:ok_hand: pardoned infraction mute for @rocky ferry.
@native tide thank u
any help ? :(
it is quite complicated
Hello, I am trying to create a web application which enables the requestor to downloads thousands of images from web. Application's end goal is to provide requestor with a URL with which he can download the images. I am looking for some help here. Can someone help how I can store images programmatically in AWS S3 bucket ? is this even possible??
i have created a project call tubers and i have 2 apps one is travello and other is tubers
i have set path and in urls.py and installed apps but it is throwing me error
use the aws sdk
Thanks for the response LP. with SDK is it possible to store images directly to cloud ?
can someone please help me
yeah
just use putobject to upload your images
presigngetobject to retrieve urls
or getobject and return yourself
Thank you!!.
@full dawn wait you want one url to download all of them?
that's not quite how object storage works
but you could zip the images i guess
did you include path('', include(apps_name.urls) in your main project app?
yes
see this bro
it shows you this error after clicking on register ?
yes
initially also it is showing me
but when i got to /home
it works
but the moment i click on register it shows me error again
give attribute name to your urls
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path("",include('travello.urls')),
path("",include('register.urls')),
#path("hello/",include('calc.urls')),
]```
this is my project url
from . import views
urlpatterns = [
path('register/',views.register)
]
this is my register app url

