#web-development
2 messages · Page 194 of 1
form = UserRegisterForm(request.POST)
this takes the POST data submitted and uses it to create a UserRegisterForm, which is a ModelForm. that's why it calls form.save()
so lets say i have a model that looks like
class User(Model):
username = models.CharField(...)
password = models.CharField(...)
age = models.IntegerField(...)
email = models.CharField(...)
Yea.. I have made one like this
right
so the example uses what's called a ModelForm
lets say you have an html form that's something like
<form method="post">
<input type="text" name="username">
...
</form>
and so on
in a view, i could access their data values by using request.POST["username"], right?
yes
so if i wanted to create a user like this, i could do
if request.method == "POST":
username = request.POST["username"]
password = request.POST["password"]
email = request.POST["email"]
age = request.POST["age"]
user = User.objects.create_user(username=username, password=password, email=email, age=age)
user.save()
ye
that's very, very tedious and repetitive, because you take the data from an object, put them into individual variables, and use those variables to create another object just to save it
modelforms come in handy and are quite useful because they make the process alot simpler and faster
Hmmm okay, I guess
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
all it takes when using a modelform
So, where does the .save() option save the data?
into the database
And how do I access that, or it can't be accessed?
you can't access it just by opening it because it's unreable to humans (hard to phrase)
you access it by querying for it
in django this is very easy
user = User.objects.get(username="pancakes")
Hmm
the queryset api is really awesome in django
I see, and the authenticate() function, it's just like User.objects.get? or something else?
the authenticate function just checks whether a set of user-provided credentials are valid
for example it checks if your username/password combo is correct
if it's correct, it returns the corresponding user object that match the credentials. else it returns None
Ok, so .authenicate() will verify if info's correct
User.objects.get() will get the info
.save() will save it to a db.
And there's no option to manually delete the entered data
right?
‘’’py
def test():
print(“is this working?”)
‘’’py
def test():
print(“is this working?”)
‘’’
user.delete()
O ok
django docs come in really handy at these sorts of things
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
and from the shell (actually, I created many accounts) ?
.
‘’’py
def test():
print(“is this working?”)
‘’’
python3 manage.py shell
from <app>.models import <whatever models u wanna use>
Help
Ohhh, got it 👍
!e
def test():
print("Is this working")
@limber flower :warning: Your eval job has completed with return code 0.
[No output]
Like this
!e
‘’’py
def test():
print(“poo poo”)
‘’’
@shadow vine :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | ‘’’py
003 | ^
004 | SyntaxError: invalid character '‘' (U+2018)
I'm getting an SMTP authentication error :/
How will I add css to the pre-made forms?
I had my own form
But.. django didn't take it
and when i'm using the pre-made ones
It doesn't put the css
You know, what can I do?
you can add html attributes to each input if you like
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['myfield'].widget.attrs.update({'class': 'myfieldclass'})
it's a bit tricky with model forms but that's the idea
how do you move an img to the top middle
part
agreed!!!
Yeah i got it with flexbox
is there a way to define a new set of allowed http methods for filters? i.e. /api/ can have get, post, but i want /api/?filter= to only have get. the solution im thinking of right now would be to create another endpoint /api/filter/ but i wanted to know if i could avoid that
which library? I think for the most part you would have to check for filter and reject a request if that’s set on a non GET request yourself
using the django rest framework and the filter comes specifically from the django-filter library
in general though, how do people usually do this? do they just leave it as is?
(Django authentication ) i am going to build the authentication like **Zoom Meet ** In which those who create the meet have to register thought username,email,password and other who wants to join just have to type(Full name ,email(optional)) and join directly the meet
- i also have to save to database which user join the meet
- the blocked users
Any suggestion for this type of user models
@stark tartan what is is that you're missing ?
Hey, I am trying to create a synchronized output for everyone using websockets in django. I have the websocket class set up, and I tried starting a "game loop" from __init__() in the websocket consumer. However, that cause a bunch of issues, and I found this: https://stackoverflow.com/questions/42564524/are-django-channels-websocketconsumers-stateless
Anybody know how I could achieve the synchronized output for everyone since I can't achieve it from within the class?
i want to implement this type of custom user
If you guys have any experience working with sockets and ngrok, I have an interesting problem I have not been able to solve combining django with sockets for networking between server and raspberrypi. Full question: https://stackoverflow.com/questions/69503197/ngrok-with-python-and-raspberry-pi
or join #help-pear
hey anybody know how to start a single loop for django that is always running? I was told somewhere that using AppConfig.ready() will run multiple times if and when I serve it with gunicorn and daphne (gunicorn for http, daphne for websockets)
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'stocks.Investor' that has not been installed
stocks is added to installed_apps and auth_user_model is also configured
How to solve this error?
Anyone know how to host django website on netlify?
idk if this is possible
https://www.reddit.com/r/djangolearning/comments/kuaixo/can_we_host_django_website_on_netlify/
4 votes and 13 comments so far on Reddit
netlify is only good for hosting static websites without backends. If you want a free option with a backend just use heroku.
You can't, unless it's completely static and using something like django-distill
maybe you need to use the full name stocks.investor in the installed_apps list
anyone has some straight forward guide on rendering a django form in bootstrap5 modal?
I am not sure how to do it, everything renders in the modal except the {{ form|crispy }}
can you explain more
it's a CRUD form that works just fine when I open on separate page. Though when I try and render it as a modal only the hardcoded HTML renders without the input fields
you want to not to reload the website and all in signle page??
yes, index displays the list of my items and there is a button on the page "add item" the is a bootstrap modal. This is where I'd like the input fields to be but only the input labels show up.
I am new to web development I have loads to learn. Sorry if this is a bad question
I have done some digging and all seems to be pointing to AJAX
can you send code??
anything in particular? as there's quite a bit, I don't want to flood the the chat with big chunks...
though than again, no worries, I came across something that might help, just need to wrap my head around it 😄
just haven't done much jQuery stuff yet, so I'll have to sink my teeth in to that a bit before I go on with this
Currently developing a multi-tenant application in Flask (requirement is to support thousands of tenants). There are no strong concerns over security so haivng a single db around will be just fine. Now, I am left wondering which would be a sensible approach:
- Having multiple schemas inside the same db
- Partition a table by a
tenat_idkey and bake the multi-tenant logic inside
I am wondering if having many schemas in a a single db might hamper admin tasks and backups.
perhaps docker-compose your application, and put your db as another container
nothing is better than docker to make multi tenancy in the smallest applied efforts
Where to put the db is not really an issue here (it'll be a CloudSQL instance on gcp). My question was more related to how to organize the models
I mean .. that u can raise separate container with db for each app container
Multi tenancy problems are solved
U have full db for each db
Lightweight as much as containers can
The problem is... If u need it persistent ;b
This solution fits only when u don't need db being persistent
Then gcp with its reliability and probably much better features is more preferable
Anyway.. I would probably make separate database inside databases. That sounds like more isolated solution
If money would allow... Then raised separated dbs with terraform
Sufficient isolation for multi tenant thing is important parameter too
Or even probably we could just plan tables to work for different apps
Then we could have same db and tables for your multi tenant thing
Actually... U know... I don't know your problem enough to make the right choice
We have too many options, and each one is having its own pros and cons
And that's perfectly fine, as I've just illustrated the vey basic gist of it. I htink for a small POC I wouldn't mind using shared tables partitioned by a tenant_id to baically flag who onws the given row. This wouldn't scale though as sharding only works with schema
Hence I think your idea of isolating things a bit more with schemas is probably the way to go
Probably the most painless option out of them for easiest maintanance
Cheers mate, thanks for the good chat
anybody want to pair program on flask? i'm a beginner but have ruby experience. Mostly for the motivational aspect and that we can code review each others work etc.
@native tide I am deciding between picking django or flask. My motivation is to build and maintain my own website 6 months down the time. BTW, i am new to the framework and python as well.
django seems to be the popular choice. I picked flask to get a more low level undrestanding of web development
Does anyone have experience starlette's SessionMiddleware? I'm using it atm, but having issues since I'm load balancing across multiple containers, so the different containers have different secret keys. Is the fix here to just hardcode a key with an env var or is there something more elegant/secure?
Can someone here please help me with my django application using heroku
like it says its deployed
and it works
but when i go on the website
it says this
To explain further, the issue arises when a user gets redirected and it get's served by another container
I have been working on this for literally 3 hours
and it keeps not wokring
if anyone could help
it would mean alot
@river raven could u possibly help
Sorry no, I have never used heroku
shit
do you have any
other like hosting services
i can use
for django applications
that worked for you @river raven
We host our PythonDiscord site using linode
I've used linode personally, and they're pretty good
it can host django applications to correct?
You can get servers and then set it up to host django, yea
FastAPI vs Flask vs Django which one's better (currently using fastapi because I've heard it's the fastest)
many people - many opinions
I know django the best, so it would always be the best for me
Like most such questions it really depends on your use case and priorities. Django is the most powerful but also the most complicated to learn and configure.
If you know FastAPI and it's working well for you then great.
I like FastAPI for smaller projects, and django if I'm combining many many things
it is much easier to use because of the built-in orm, which removes 80% of problems, which you get using the other frameworks
pythonanywhere.com is a free option
What is the difference Between Flask and Django if some one can illustrate (Features, technology..)
Flask has less features out of the box, while Django comes with everything built in
In flask i can handle for example ban IP and detect number of requests and this issues or is it only and best be done with a Django
i mean like website security against DDOS, Scrapers etc..
django has many of them built-in
flask - not, afaik
Okay Thx alot
flask is good for novices to get it, less learning curve I guess.
but at the same time... since flask is not having built ins, it gives you freedom to do everything on your own, which will lead to shitcode more high likely 😉
django with its train on rails approach will save you from it, as long as you just use its features, instead of trying to reinvent the wheel
Okay thx
btw, there is third option, FastAPI is quite popular too in job market
although I should say its second option
because flask is not really valid for jobs, only django and fastapi are
so basicaly Flask is an educational and introductory for python web development, Django and FastAPI are products for business
👍
at the moment, yes
but it can change
question
what is a good cheap vps provider
I'm getting bored of waiting for Kimsufi to restock their $5.99 vps'
I need a cheap vps to run a MediaWiki install for a wiki I'm creating about Team Fortress 2 cut content
i don't, just heard it's the fastest so i went along with it and started using it
dm if somebody can make me website
Hello everyone. do you have experience with gzip on heroku?
aahhh
getting error
;-;
Using django. when I try and do this:
def save(self):
super().save()
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)
``` I get error. But without it, no error.
Don't listen to the haters, Flask is even more widely used In production than Django (https://www.statista.com/statistics/1124699/worldwide-developer-survey-most-used-frameworks-web/). I know a number of people who use Flask more than Django professionally. It's just that you only use Flask for APIs and other very simple things. Django is more appropriate for full-featured websites
lets fix it to check in job market, checking mine:
495 django
200 fastapi
300 flask
uh. flask is used even in mine, all right.
Django is still leader anyway ;b
"more widely used" doesn't mean "better"
cries in Angular
indeed.
the thing that you can make a full crap easily with Flask is still remaining
Django protects from mistakes better ;b
still tempting to go for Svelte instead of trying event Vue ;b
tried Svelte already, its tutorial and easiness to use is totally awesome
Svelte is definitely awesome ;b
if I ever
clean, and easy peasy
with Svelte I learn what's pure CSS/javascript
instead of the...
framework shenanigans above it
Svelte shenanigans are learned within one day hour
I didn't say better. I was responding to the false statements that Flask isn't used for business when it definitely is.
wups mb
that's true
Hi, any Flask pros here? I have two routes, one returning some text, and the other an image. Could I return these at the same time, as to not double the computation time?
so i never stumbled upon the helpful advice of using virtual environment for your django app so now i have a bunch of stuff in my requirements.txt that i don't know if i actually need, do i just delete it and go the manual way of adding requirements?
or is there an easier way to sort out the mess
Already fixed this myself - for reference: export images as base64 encoded, combine in. json
I guess I would create a fresh venv, add your project, install missing packages until your app works, export the requirements from that
got it, thanks
https://pastecord.com/cykotesiqi.py
HOW TO ACCESSES THE MEETING CODE WHEN I SEND THE SUBMIT THE FORM (THAT I SENDED BY GET REQUEST PREVIOUSLY)
Is there any chance mui is available for outside of react?
do i add the venv folders to gitignore or not?
edit: yes i should gitignore them
definitely
night everyone, so i am newbie here, and i try to return redirect back, and i reseach but im not find them, can anyone help me
?
Looking for advacne DRF dev?
Hello any good book or website where i can learn web developement im pretty new to python and i did tried and did probably basic concepts still trying to learn more of it so i would like a book suggestions
[Q] Beautiful Soup / Web Scrape - easy:
Hi, how to scrape 2x tags: a with class linkme and p with class price?
HTML:
<div class="offer">
<a class="linkme">The item aaa</a> || <p class="price">$100</p>
</div>
So how to scrape "The item aaa" from <a class="linkme"> AND price from <p class="price">
@latent cosmos response.xpath("//div[@class='offer']/a/text()").get() +" "+response.xpath("//div[@class='offer']//p[@class='price']/text()").get()
A guide for how to ask good questions in our community.
this book for example or official django docs, they have nice tutorial in getting started
https://docs.djangoproject.com/en/3.1/
A guide for how to ask good questions in our community.
Ok😁
Can you make a fully featured/stylized website using Django?
Without the use of CSS/Javascript?
No, CSS is your styling. You can use libraries to help with this but in the end it is all CSS in your HTML that applies styling.
JS is for functionality mostly.
You can build without JS for the most part, as long as you don't need live changes to the page (aka without refresh).
I don't know what you mean by fully featured, but you likely will need css and js to do that.
Thank you - the 'feature' I'm aiming for is dynamic updates on the page without having to refresh, so it looks like I have to dive into JS - what is the benefit of using Django over just a dynamic webpage using CSS and JS?
I'm not sure you can compare it that way. Django performs your backend functionality while HTML, CSS and JS are handled on the front-end. Django just tells your pages what data to show via views. Django does serve the html via templates, but the CSS and JS is all done on the front-end.
It's not either or, they go hand in hand.
the lazeiest solution would be to apply CSS framework like bootstrap
it would allow you write fully featured web site almost without touching css
If you're asking why Django and not something else for the backend, then that depends on what you want the backend to be able to do and what you need out of it.
well...
technically the person can go without javascript as well
POST requests bring sufficient minimal interactivity to the site
we just return to the fully server side sessional times
but knowing CSS and javascript (and frontend framework) will make a magnitude better work ;b
without it, you will be in a certain limitations in what you can do
I'm pretty sure you can't make live changes without JS.
depending on what you consider live
A change to the DOM without refreshing.
but all those Forms work without JS by default
yes, we can't (or at least I don't know ways without JS 🤔 )
we return to the old times where we need request per every change ;b
it still allows using Forms for logins, Submitting msgs, having videos and e.t.c.
the Ai chat bot is made by Django or is it made by javascript
no idea how your AI is made, just some simple python logic I guess for example?
but chat is made with web sockets stuff, as example to make it Django Channels + Javascript are required both
I am working on a front end application in reactJS. Which is hosted with a domain A.com. A few images are being served from a different static content end point B-test.com. The domains are different for test and prod. B-prod.com.
Now I don’t want to inject this as an env variable during compile time. Is there an alternative ?
Working on basic html templating and Jinja 2 is throwing the error
jinja2.exceptions.TemplateAssertionError: block 'title' defined twice
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>{% block title %}{% endblock %} - My Webpage</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<p>TEST</p>
<!-- {% block title %}{% endblock %} -->
<script src="" async defer></script>
</body>
</html>
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
Not sure why though
I linked it with block title, the associated documentation
https://jinja.palletsprojects.com/en/3.0.x/templates/#child-template
somehow works but its not feeding any errors
when i run through the documentation which means user error on my end
but im not sure what im getting wrong
Help?
Total abuse of @ function but do you have a minute?
@vestal hound
@runic lodge the title is defined twice the second one is commented out of the HTML but not out of the template, it's a common mistake. To comment in Jinja you need to use {# #}
@lilac solar oh i see i thought i was referencing it in the first html doc, how do i reference it in the html doc?
{ self.title} ?
You have it defined twice in the base.html which is what Jinja is complaining about. Line 6 & line 17
check
but if i wanted to inherit it into the
<title>{% block title %}{% endblock %} - My Webpage</title>
block how would i go about doing that
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
This is correct
would i just leave the title blank then?
What are you trying to achieve?
I want "homepage" shown in the second block of code to render in the title position of the base layout
located within the head of the first bit of code
In that case, just delete or correctly comment out line 17 in base.html
if you want to comment it correctly it need to be <!-- {# block title #}{# endblock #} --> instead of <!-- {% block title %}{% endblock %} -->
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
{# block content #}
<h1>Test But bigger</h1>
{# endblock #}
so like this?
Let me re-reference what im trying to do.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>{{ self.title }}</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<p>TEST</p>
<!-- {% block title %}{% endblock %} -->
<script src="" async defer></script>
</body>
</html>
The position of self.title needs to be populated with what is in the index.html file, this one.
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
{# block content #}
<h1>Test But bigger</h1>
{# endblock #}
Sorry dots not meaning to be condescending.
Your inherited template is fine. Your base.html needs to be as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>{% block title %}{% endblock %}</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<p>TEST</p>
<script src="" async defer></script>
</body>
</html>```
ahhhhh i see now
I don't know much about templating with Jinja2, sorry
@calm plume all good, it's fixed
@lilac solar thank you, this is better, so html inheritance in jinja 2 is referenced sequentially like a stack
as in it cannot be unordered or can it?
I think it can be unordered, but the identifiers for blocks must be unique across the template inheritance tree/stack
got it, it's probably good practice to have it ordered
I wish there was a way to give points here, appreciate it none the less
Hello! I’m legit new to web dev and trying to get use to this how would I add images? I’m on windows
And fonts
Hey
for images, use the <img> tag
Google fonts has pretty good dev help
Here's an example with both
<html>
<head>
<style>
@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
.some-class {
font-family: 'Roboto';
}
</style>
</head>
<body>
<p>Not in roboto</p>
<p class="some-class">Epic text in roboto</p>
<!-- Add file path or url to image src -->
<img src="/img.png">
</body>
</html>
@night junco
Legend!
Hello, feel free to dm me the answer or just say it in here, but what classifies the use of a database on a website and what would you use for it. In this scenario it an online airplane parts company, needs to be able to have its customers place orders for parts in the store inventory
is a sqlite db recommended for a site handling over 100 r/w requests at the same time
try to make PostgreSQL as your database
because having website in same server with database might make it easy for hackers to delete and obtain your data
I doubt that
Having a website and a database together could actually be a really good thing
The connection would never even have to leave the server
Yeah, especially if you have low to medium traffic
I'm new to django
Im a bit confused about whether I should create a separate app for user authentication
Or just do everything in the same app
I'll eventually have to extend the users model and link it with a database in another app
How do you decide whether to create a new app for something 🤔
also ping me if you reply please thanks
Hello, Can somebody please help me with a Bootstrap Hamburger Icon Toggling problem? The menu is not toggling when clicked.
I wish to take a 800x800 SVG from my index.html and send it to the bottom of the same page as a thumbnail when user clicks a button, and allow the user to generate another SVG. and so on... Any tips on where I should be looking for such examples?
Alternately, its even ok to create a slide-show with subsequent images.
can anyone help me to make a resize image system, when uploading image using form, in django python, I've tried about 4 or 5 ways, and it doesn't work (im newbie)
I'm trying to modify a client that allows/facilitates it. It allows me to edit the css but not the html.
This is the html: html <div class="sc-hBEYId jgcjMZ"><span class="detail"><span class="author">Fenton</span><div class="sc-fodVek Qskju"><time>Today at 04:09</time></div></span><span class="_markdown_8b8eo_2"><p>What's the class for the blob thing behind server icons?</p> </span></div>
This is what i'd like, essentially:
background-image: url("https://i64.servimg.com/u/f64/12/23/10/57/glitte10.gif");
}```
ping on response pls
Hey, How can i fix this? under my body's size is related to the content of the table. the more row in the table the bigger the body gets and thats why its making so much uneeded white space under the footer thats not used for anything
i tried doing the following but nothing changed
body, html {
height: 100%;
}
Is there anything wrong with using a REST API for a chat app? Or is a websocket based approach better
I'm not great at CSS but try position:absolute;
you do probably want websockets just to have messages appear instantly, rather than after the client asks
REST does have a resource type for server push, but it works using callback urls, which won't work for a chat app
So will it work with REST or do I need to learn websockets
it is possible, but websockets are the better tool to use
This is what happens with ```css
body, html {
height: 100%;
position: absolute;
}
Thanks :)
Try 100vh?
same outcome as the above photo
Can someone give me a comparison on using flask vs quart for executing bot commands?
CSS question:
I have an <a> element which i'm trying to style.
I use float to move it to the right, and position to center it vertically.
Here's its code:
a {
position: relative;
line-height: 0;
padding: 10px;
float: right;
top: 50%;
}
Weirdly enough, top does not respect the padding, meaning the text is not centered.
Although, i've came up with a solution:
top: calc(50% - 10px)
The only problem with it is that i want it to automatically take padding's value, and put it in the calc() function.
Any ideas?
afaik there's no way to reference another property in CSS, so you'd have to do this via some sort of backend like JS
i see. welp, thanks for your help.
Hi there! I have a general question about full-stack development: I'm building a frontend SPA with React and on the backend side I have Azure API Manager that serve the endpoints I need in a REST Api, discussing with my team we thought about the idea of inserting a web server as a middleware between the API and the frontend, the main purpose is to hide the API endpoint url and maybe use it to do some fields checks, is this middleware server useful in your opinion or it's only a resource/performance waste?
Thanks in advice!
If by Azure API Manger you mean this: https://azure.microsoft.com/en-gb/services/api-management/ then I wouldn't bother with a web server. I would expect this management layer to bring together several services into a unified endpoint. If you want to field checks etc I would expect that to happen in the API manager or in the services behind it
To answer your immediate question: You could use CSS variables here: https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties
Generally though I stick to flexbox or grid when it comes to layouts as I personally find them easier to understand and more predictable. That said, I have no greater context to your code so won't comment further
hey i was wondering if there was someone who knows how django-helpdesk works and could help me in VC i have some trouble with writing my problems down bcs my English is bad so could someone help me ? (if there's someone who knows how to speak french too it could help me a lot but i still can understand English)
I'll try
Hi, I need to create First In - First Out Queue with Django Rest Framework,
where multiple users will have access to endpoint which returns first created Contact Instance, but there can't be the situation where few users will get the same contact.
So i figured out that i could edit a single field "task" on every get request and add "if" to queryset which would return only the contacts where task field is equal None/ "New".
Meanwhile if any user would send get request to that endpoint then the task field would be set to "Processing" or something like that.
But im not sure how to achieve that. I wish i could do that like this
Contact.objects.filter(task="New").first().update(task="Processing")
Is it possible with signals? or i should check the guide about tool called Celery? or something else i don't know about?
not sure if this is a right area for this but how do I send out and receive HTTP requests?
Hey guys, I just hosted this website that's built using Flask + React. The idea is that it would allow users to comment easily & quickly on YouTube videos that have blocked their comment section. I'd like to hear your thoughts (i'm thinking whether to continue working on this or no). Here's the link: https://make-a-comment-on.herokuapp.com/
Web site created using create-react-app
Any front end devs in the house?
You can send with requests, it's very simple. Not sure about receiving but I guess sockets might work.
!d requests
Currently the most popular synchronous library to make HTTP requests in Python.
it depends on the use case
you can use ImageField in your model
Does anyone know how we can fetch data from the database using dropdowns in Django?
I tried so many things nothing's working
can you show me your views ?
@mystic wyvern hey wanna try to help me
yes i hope
Bro i know that there is thing like imagefield but i dont know where and how to store the data
Imagefield has parameter upload_to but idk what is that
yep but i haven't use it a lot
this where the image is saved
I want to save images somewhere and then get images by an ID
you just save the dir in the database the not the image
Oh how to make that?
so the thing when im adding any post from admin panel without thumbnail , it's loading default img by signals
but when im upload new post without thumbnail from frontend it's throwing error
while when i upload it thumbnail on both admin and frontend it works fine
@login_required
@cache_page(60*2)
def notes_upload(request):
if request.method=='POST':
title=request.POST.get('title')
subject=request.POST.get('subject')
desc=request.POST.get('desc')
thumbnail=request.FILES.get('thumbnail')
file=request.FILES['file']
author=request.user
entry=Notes(title=title,subject=subject,desc=desc,thumbnail=thumbnail,file=file,author=author,published_on=datetime.now())
print(thumbnail)
entry.save()
messages.info(request,'Notes updated successfully!')
return HttpResponseRedirect('/')```
as admin is working fine == models.py is correct
problem is surely here or in html
you should put somthings call MEDIA_URL and MEDIA_ROOT
Where?
in settings.py
Is this the section to ask about something like web scraping and CSS selection of scraped data?
u can ask css n scraping yes
what the error says
i couldn't understand that : (
so for something like the following:
quotes.css('span:not([class])').css('small.author::text').get()
is it possible to combine those two .css() into one somehow?
ValueError at /notes/5/
The 'thumbnail' attribute has no file associated with it.```
main prob with this error is it saves info to db then shows error + it renders on home page it's slug and when i go to paigiated shows error
hold on
this is a perfect video to understand
In this video I'll show you how to upload images using Django.
We'll set up the ability to upload a header image for each blog post. Uploading images with Django is pretty simple, we need to add a field to our database model, then make a quick change to our settings.py file, and our original urls.py file. Then tweak our blog post form, and t...
thanks
are you use a django form or html form ?
ofc html
can you show it ?
<main id="upload">
<div class="title">
Upload Notes
</div>
{% if messages %}
<div class="error">
{% for msg2 in messages %}
{{msg2}}
{% endfor %}
{% endif %}
</div>
<form method="POST" enctype="multipart/form-data" >
{% csrf_token %}
<div class="field">
<label for="title">
Title
</label>
<input type="text" name="title" placeholder="video's title" required name="title">
</div>
<div class="field">
<label for="subject">
Subject
</label>
<input type="text" name="subject" placeholder="Subject">
</div>
<div class="field">
<label for="vid_desc">
Description
</label>
<textarea id="desc" name="desc" cols="30" rows="10"></textarea>
</div>
<div class="field">
<label for="thumbnail">
Upload Thumbnail
</label>
<input type="file" id="thumbnail" name="thumbnail">
</div>
<div class="field">
<label for="file">
Upload Notes
</label>
<input type="file" required name="file" accept="pdf,doc,docx">
</div>
<br>
<button class="submit">Upload</button>
</form>
</main>```
<form method="POST" enctype="multipart/form-data" >
<div class="field">
<label for="thumbnail">
Upload Thumbnail
</label>
<input type="file" id="thumbnail" name="thumbnail">
</div>``` focus here
ig here only cez from admin working fine
i guess something that is when you write here thumbnail=request.FILES.get('thumbnail') and you didn't give it a thumbnail it show error bcz it cant get any data
in another hand, there is nothing to get
@dusk portal
i think you can do something like that thumbnail=request.FILES.get('thumbnail',Flase) to skip if there not any data
If I want to learn flask, what languages should I learn to be able to make a website
for backend (flask) python and for frontend you should learn a few things like (html, css , javascript )
At what level should I learn those languages in order to make a decent website(I know this is general, I am sorry about that I just don't know what I should do with flask yet)
you can now move on with flask and html,css you can skip javascript right now
def members():
try:
print(request.form["invite"])
except:
return render_template('members.html')```
This is my app.py its flask and html, bnut i cant get to find the invite link
```<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Detective Voke's API</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<header>
<div class="wrapper">
<div class="logo">
<img src="" alt="">
</div>
<ul class="nav-area">
<li><a href="http://127.0.0.1:5000/">Home</a></li>
<li><a href="http://127.0.0.1:5000/panel">Panel</a></li>
</ul>
</div>
<div class="welcome-text2">
<h1>
Discord Members<span></span></h1>
<h1>Enter Invite</h1>
<form method="POST" action="/members/api">
<div class="memberinput">
<input type="text" name='invite', size="50" height="50" color="transparent">
<h1>Enter Key</h1>
<div class="memberinput">
<input type="text" name='key', size="50" height="50" color="transparent">
<h1> </h1>
</div>
</div>
<ul class="nav-area">
<li><a href="">Start</a></li>
</form>
</ul>
</div>
</header>
</body>
</html>```
idk why no owkr
tbhj
look into how to render an html template through flask
wdym
can you past the error you are getting?
its just not sending the requests
@app.route("/members", methods=['GET', 'POST'])
def members():
try:
print(request.form["invite"])
except:
return render_template('members.html')
@app.route("/members/api", methods=['GET', 'POST'])
def member(invite, key):
return invite, key
but when i fill it in
it just resets as its sending to the render_template
sure
you havent defined the job_elements object @native tide
@native tide what happens if you remove the try/except and just leave return render_template('members.html')
can you not get from it?
you need to define the job_elements object, how you do it is up to you.
what tutorial are you following?
@app.route("/members", methods=['GET', 'POST'])
def members():
if request.method == "POST":
invite = request.form['invite']
print(invite)
return render_template('members.html')
thats what it was
but it just doesnt work
lmao
nice
that makes sense
ah dang
youre missing this line job_elements = results.find_all("div", class_="card-content")
its in the tutorial
how are you testing the POST?
<form method="POST" action="/members">
<div class="memberinput">
<input type="text" name='invite', size="50" height="50" color="transparent">
<h1>Enter Key</h1>
<div class="memberinput">
<input type="text" name='key', size="50" height="50" color="transparent">
<h1> </h1>
</div>
</div>
<li><a href="">Start</a></li>
</form>
browser*
that not the request, that's the return.
Are you connecting to the endpoint with your browser?
try removing the "GET" and leave just the POST
i just need to get the invite so i can send the invite into a channel
in the flask file
already done that
and still just GETs?
but if you leave the GET then it allws that request?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Detective Voke's API</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<header>
<div class="wrapper">
<div class="logo">
<img src="" alt="">
</div>
<ul class="nav-area">
<li><a href="http://127.0.0.1:5000/">Home</a></li>
<li><a href="http://127.0.0.1:5000/panel">Panel</a></li>
</ul>
</div>
<div class="welcome-text2">
<h1>
Discord Members<span></span></h1>
<h1>Enter Invite</h1>
<form method="post" action="/members">
<div class="memberinput">
<input type="text" name='invite', size="50" height="50" color="transparent">
<h1>Enter Key</h1>
<div class="memberinput">
<input type="text" name='key', size="50" height="50" color="transparent">
<h1> </h1>
</div>
</div>
<li><a href="">Start</a></li>
</form>
</div>
</header>
</body>
</html>
check request.form.get('invite') instead of request.form['invite']
its not that
the request is a get request
when it is cleartly a post request
<form method="post" action="/members">
hence
post
try to do a print statement
did it return a value?
127.0.0.1 - - [12/Oct/2021 20:06:05] "GET /members HTTP/1.1" 200 -
127.0.0.1 - - [12/Oct/2021 20:06:05] "GET /static/style.css HTTP/1.1" 304 -
127.0.0.1 - - [12/Oct/2021 20:06:07] "GET /members HTTP/1.1" 200 -
127.0.0.1 - - [12/Oct/2021 20:06:07] "GET /static/style.css HTTP/1.1" 304 -
see
no
hey i watched this video ! it worked but data only shows on django admin page. it doesn't shows on database
it returns as a get request.
omg
its sending as a GET REQUESTS
this is if its a POST REQUEST
/
SEE
it wont change shit
...
wow
@native tide Maybe you shouldn't ask for help since you know how to code.
no one is questioning how you code my friend
aight
yall are useless as shit
ong
Glad to help when someone is courteous about it. Go fix it yourself.
yeah fuck that guy, can't even explain his problem
def signup():
if request.method == 'POST':
username = request.form.get('username')
email = request.form.get('email')
password1 = request.form.get('password1')
password2 = request.form.get('password2')
this is how i do it and it works well
@native tide maybe you added it too early? add it under the "results" variable
no I was talking about Detective Voke
did the error at least change?
do i need to learn OOP well befor starting Django and Tkinter apps for better understanding and code?
if so i need good references please ❤️
its find_all not findall
Can you show the code and what's around it?
Specifically, what's before the class that you defined?
you have issues in your loop, it should be job_result not jobresult
for job_element in job_elements:
title_element = jobelement.find("h2", class="title")
company_element = jobelement.find("h3", class="company")
location_element = jobelement.find("p", class="location")
Should be
title_element = job_element.find("h2", class="title")
It's class_, not class. https://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class
Glad I could help 🙂
Nice!
Nope, you can simply use function-based views.
At least for Django
i mean for clean functioning and code
happy hacking 🙂
What?
I mean i saw some people make tkinter codes for like top level etc in classes
That's how Django functions.
it was so clean
I don't know about tkinter.
okay thanks
Classes are an option, sure.
for Javascript some times you need to disable javascript from the browser to see if the data you need is rendered by JS or not
if it is use splash or Selenium
Hello guys !Can someone tell me what best programming language for backend ?
Python (Django,FastAPI and Flask) , Javascript (Node.js)
Thanks!
np
Hey all, can you help me with my poorly explained issue that I will give you more information about but you'll have to fight me for it each time and then I can get mad and tell you off because I don't understand your answer/am incapable of thinking laterally
Hey, anyone got an idea on how to fix this? my body doesnt seem to be full size and only gets bigger the more content there is. Iv tried the following CSS but it doesnt change anything. Iv been stuck for a whole day on it. ```css
html, body {
height: 100%;
}
Try height: 100vh on body
Hey
nothing happens
what are things i should look for to put in a personal website? i wanna make a portfolio but i'm not sure how to showcase myself
I have an instance hosted, i want to run a flask app on a specific port, when i tried using app.run(host='0.0.0.0', port=1234), i cannot access it with public IP, anybody know how to use the public IP?
Are you forwarding the port?
Does your host whitelist the ports? It may give you a PORT variable to use.
i accessed it from my browser with http://ip:1234, but i used sudo ufw allow 1234/tcp
You port forward in your router config
A port forward is a way of making a computer on your home or business network accessible to computers on the internet even though they are behind a router. It is commonly used in gaming security camera setup voice over ip and downloading files.
i have it hosted on aws
i have another flask app running with apache2, it works fine and i can access it
I believe in aws, all outside traffic goes through the reverse proxy
Or at least you should configure it to do so
hmm
oh btw, when i use 0.0.0.0 as host in flask, it hosts in the local IP shown
tried to use the public ip too, didnt work, it gives error no.99
Is it the public ip, or the local ip?
You can't bind to an address you don't have
0.0.0.0 just means bind to all interfaces
the ip i usually use to access from browser
Is it the ip that shows up in the ip addr command?
the ip that shows up in ip addr is just local, 127.0.0.1
ok no its not the ip that shows in ip addr
Then how are you connected?
i use ssh -i auth.pem ubuntu@ip
127.0.0.1 is just localhost
ik
i tried to run flask with the ip in here, but error no 99
Theres 3 IPs, the localhost (127.0.0.1), the local IP, and the public ip (which can be accessed anywhere) right?
i can access my instance using ssh and with the public ip
i want to host flask app in the public ip, but in a specific port
hey, I was trying to deploy a machine learning model on Django. can anybody help me
just ask
I have a trained PyTorch and I want to deploy it using Django. when I give both solvent and solute it should predict the energy
I have made this interface using forms in Html. when I search on the internet they are saying do the serialization. It's so confusing
html page
please point out what should i need to do next
Flase?
@native tide I don't know what the internet means by serializing, I don't think you need to do anything like that
you could make your <form action="" method="POST"
and then edit your homepage view to handle a POST and GET request
then you can get your form inputs using request.POST.get('solute') or something like that
you need to name your inputs too <input name='solute'
what should i need to keep for action=??
in <forms> add method='POST'
'directory recivin gthis input I am not rendering any page i was just taking response from two fields in models
your not rendering the page
your giving it a pathway to send this data to
and in the < input attributes
you should enter any name for input to identifiy it as key later such as name='input1' id ='input1'
so when you call for it on python side you type in this code request.form.get('input1')
<input name = 'email' id='email type='email' placeholder='Please enter your email'></input>
this is an example..
Is someone able to help me upload my django site to my website? I am using godaddy
any decent library which can escape JSON strings to be safely output into JS from Python? e.g. var foo = "</script>" causes issues so just json.dumps("</script>") is not enough
..
..
..
..
this seems pretty simple https://github.com/yourcelf/escapejson/blob/master/escapejson/escapejson.py
how do I make django auto-refresh the server when a non-django script is updated?
in this case brython
oh nvm I'm an idiot
pyweek champion's are saying themself idiot wow
is django required to build a py web?
How good is Cloudflare for hobbyists
Hello guys i got a question :
Say i got a Comment section with x amount of likes and i have two different people viewing that website at the same time,
Say one of them likes it , so the database updates ,
How do i make it so it re-renders the amount of likes to the other person
My question is , How to change what a user sees on his screen when the data in the database changes or updates
Hi, i have a bunch of questions, im currently learning Spring-boot (java) and Angular, I was suggested to check out some python implementations because my project wont need the overhead and scalability that those have.
I have seen a tiny bit of DJango and heard about something called flask but this can apply to any in particular.
Here are my questions:
is it something better to avoid if using an OOP design?
can they use html/css/scss?
^ follow up can they use bootstrap?
is it limited to a specific DB?
Is there adequate security, user registration, role management included or 3rd party imports that support it?
Is it reliable?
Apologies for the spam, just trying to get a feel/opinions before I dive into research - i've already swapped out technology like two/three times'
im not sure when it comes to python but is that not bound if you are using something like MVVM design?
is it something better to avoid if using an OOP design?: Flask, Django, Fast API and any other framework and python are fully OOP compatible.
can they use html/css/scss?: Yes, although it is backend framework. While they can work with html/css, they aren't really meant for extensive javascript usage.
Better to turn them on into REST JSON API mode and use it appripriately with frontend frameworks (Angular/React/Vue and e.t.c.)
Django REST: https://www.django-rest-framework.org/
P.S. i don't know about scss, because never used it.
^ follow up can they use bootstrap? Yes. I already did it. Essentially python frameworks give you only Jinja2 templating syntax {{variable}} {{for each element}} write stuff {{end for each}}. But nothing from javascript syntax (no mounts and e.t.c.)
is it limited to a specific DB? Flask/FastAPI has no limits. Whatever database connecting library you will install, that you can use, I could recommend SQLAclehmy for flask for example.
in django case... it involves a lot of 'train on rails' approach, it has already inbuilt DB library Django ORM. From SQL database family better to use compatible with with the library dbs (for example postgresql is prefered u ll get the most amount of features, although MySQL and others you can use too). NoSQL dbs have no limits, but better to see Django Cache compatible ones.
Is there adequate security, user registration, role management included or 3rd party imports that support it? Django is certainly battery included with everything. Flask is definitely not, it follows microframework approach.
Is it reliable? Sure. I would recommend Django, it helps to make as less mistake as possible, as long as you use inbuilt "train on rails" libraries.
Is there a good Django or Flask course/content that’s a bit challenging? I’ve heard about Corey Schafer but I want to hear what are y’all’s thoughts
I prefer less handholding
Challenging meaning you know the basics?
Any particular thing about it you want to learn how to use?
Hello guys!
I have a problem
How to get data from database in django and loop through it to get image, name , surname and other data
i want to loop this
<ol>
<li><img src="../../media/{{img}}">{{ first_name }} {{ last_name }}</li>
</ol>
``` to get list of everyone in the database
**Authorization using Casbin for a Flask Project
**
I am using flask-jwt-extended for authentication in my project. Right now, I have few custom fields like isAdmin, isSuperAdmin in user table for authorization purpose.
However, I want to have dynamic roles and have RBAC in my project. While trying Casbin, I can see it is capable to do RBAC. But, even if I use Casbin I have to create the policy table for Casbin from my project and the policy table should be dynamic.
I was wondering, if all Casbin really does is look into policy table and say whether an entity is accessible or not, then why use it altogether, I can just write few functions to go through my DB and perform the authorization.
Please kindly let me know if I am missing something.
Also, how scalable is the combination of Flask, Casbin and MongoDB if anyone has tried this stack? I was thinking to use Pymongo Adapter for Casbin.
Hey! Has anyone ever deployed a Flask App on Docker? I am able to make the docker image, it's even running but not showing on localhost. I am currently using Windows 10 OS
I appreciate the time you spend to reply to these questions. Thanks
hey guys
I'm trying to center a table in a modal, but unfortunately I don't quite get how to make it. I tried "text-align" in css, but it is not helping. I had to implement padding-left with 11%, but I don't get what and why it is 11% (of what?). Could anyone explain to me how to do this?
<div class="modal-content">
<span class="close">×</span>
<table>
<th>In our offer we have:</th>
<tr>
<td>X</td>
</tr>
<tr>
<td>Y</td>
</tr>
<tr>
<td>Z</td>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td>3</td>
</tr>
</table>
</div>```
table {
display: block;
padding-left: 11%;
margin-left: auto;
margin-right: auto;
width: 40%;
display: inline-block;
background-color: rgb(6, 163, 40);
/* text-align: center; */
border-radius: 5px;
}```
.modal-content {
background-color: #97adc2;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
border-radius: 10px;
font-family: sans-serif;
font-size: 20px;
text-align: center;
}
in this state it looks like the table is in center, but when I expand or compress the site, it's going off, it's not in the center like the rest of the site
text-align: center in table style does nothing
in 50% zoom it looks like this:
how to make it in the center for good?
the green color of the table is just for reference, to see where are the borders of table
hello
!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.pythondiscord.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.
where is your static directory located?
also if using flask, recommendation is to use {{url_for('static/path/to/file/', filename='filename.ext')}}
in your html template
from flask import Flask, render_template
app = Flask(name)
@app.route('/')
def hello_world():
return render_template("index.html")
@app.route('/about')
def about():
return "<h1>About Page</h1>"
if name == 'main':
app.run(debug=True)
it worked before until i changed my code around
only the code
<!DOCTYPE html>
<html>
<head>
<title>Clicker</title>
<meta charset="UTF-8" />
<link rel="stylesheet" href="static/css/style.css" />
<script src="static/js/myjs.js" type="module"></script>
</head>
<body>
<div class="cont">
<label id="progresslabel" for="file">Progress to Level</label>
<progress id="file" value="" max=""></progress>
<!-- bar stays same length even after changing max which is good -->
</div>
<div class="btn-wrap">
<button id="btnLevel" data-func="levelUp" disabled>
<img src="static\images\level.png" />
</button>
<button id="btnCookie" data-func="click">
<img src="static\images\cookie.png" />
</button>
<button id="btnMenu" data-func="menu">
<img src="static\images\list.png" />
</button>
</div>
<!-- # is for id and . is for class-->
</body>
</html>
change your href when linking stylesheet to: {{ url_for('static/css', filename='style.css') }}
{{ url_for('static/css', filename='style.css') }}
this is the preferred way of referencing static files within your templates
app = Flask(__name__, static_url_path='')
excellent
hey i am going to build the video chat website using django WEB-RTC with django channels please give some docs or any suggestion is it possible to do this ??
I think WEBRTC requires messaging server I can use DC with it
Or React will fine
from flask import Flask, render_template, request
from flask_mysqldb import MySQL
app = Flask(name)
app.config['MySQL_HOST']: "localhost"
app.config['MySQL_USER']: "root"
app.config['MySQL_PASSWORD']: "password"
app.config['MySQL_DB']: "flasktest"
mysql = MySQL(app)
@app.route("/", methods=['GET', 'POST'])
def loginpage():
if request.method == 'POST':
userlogin = request.form
password = userlogin["password"]
email = userlogin["email"]
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM details WHERE email = %s AND password = %s', (email, password))
details = cur.fetchone()
print(details)
cur.close()
return "success"
return render_template('loginpage.html') error :-MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'balla'@'localhost' (using password: NO)")
127.0.0.1 - - [13/Oct/2021 22:19:46] "POST / HTTP/1.1" 500 -
you entered incorrect password or username
@spark dagger shall I try it then we will discuss
can you pls help point out as to why for root i am getting balla as the username ?
correct this one
enter you db username and password
it will work
yup both are webscokets implementations
I built a test application with DC and Webrtc it works.. now I am working with Google meet like project
Is anybody is Webrtc expert are you @spark dagger ??
not me lol
Okay 😩 let me try it
Would it be sane to just use a sqlite database in a Docker container plus dynamodb backed sessions ?
CSS question (again(:
I have a <div> and an <a>.
I'm trying to use padding to vertically stretch the <a>, I'm doing that with 100% unit. With height it respects the height, but not centers the text...
We're talking maybe a hundred users in total for this important but low volume app.
can u accept friend req
@shadow vine
Hi
I'd like to start a project together with a buddy. I'd like to practice backend development, as this is a huge black-box for me. The only question I've is how do I deploy the backend so that my buddy can develop the UI for the frontend using the provided interfaces / APIs / endpoints?
Has anyone tried to host with heroku before?
I'm trying to push a node.js file with yarn gulp and a few other dependencies but it's not deploying the front end. The log information is as follows
-----> Building on the Heroku-20 stack
-----> Using buildpack: heroku/nodejs
-----> Node.js app detected
-----> Creating runtime environment
NPM_CONFIG_LOGLEVEL=error
USE_YARN_CACHE=true
NODE_VERBOSE=false
NODE_ENV=production
NODE_MODULES_CACHE=true
-----> Installing binaries
engines.node (package.json): v10.19.0
engines.npm (package.json): unspecified (use default)
engines.yarn (package.json): unspecified (use default)
Resolving node version v10.19.0...
Downloading and installing node 10.19.0...
Using default npm version: 6.13.4
Resolving yarn version 1.22.x...
Downloading and installing yarn (1.22.15)
Installed yarn 1.22.15
-----> Restoring cache
- yarn cache
-----> Installing dependencies
Installing node modules (yarn.lock)
yarn install v1.22.15
[1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.2.4: The platform "linux" is incompatible with this module.
info "fsevents@1.2.4" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
Done in 13.90s.
-----> Build
-----> Pruning devDependencies
yarn install v1.22.15
[1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.2.4: The platform "linux" is incompatible with this module.
info "fsevents@1.2.4" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
warning Ignored scripts due to flag.
Done in 4.48s.
-----> Caching build
- yarn cache
-----> Build succeeded!
! This app may not specify any way to start a node process
https://devcenter.heroku.com/articles/nodejs-support#default-web-process-type
-----> Discovering process types
Procfile declares types -> (none)
Default types for buildpack -> web
-----> Compressing...
Done: 40.6M
-----> Launching...
Released v5
But I'm not seeing what errors it's throwing at me.
The only one is
info fsevents@1.2.4: The platform "linux" is incompatible with this module.
in django form what attr do i need to set a default value to a MultipleChoiceField? and to have the said field disabled? (greyed out)
I don't know what else is wrong, but know that this error is irrelevant. It doesn't mean anything.
would you like to see the directed package folder that gulp uses?
I've never used gulp, so I doubt I'd be of much help
{
"name": "particle",
"version": "1.0.0",
"description": "An awesome app.",
"main": "index.js",
"engines": {
"node": "v10.19.0",
"yarn": "1.22.13"
},
"scripts": {
"start": "gulp"
},
"author": "",
"license": "ISC",
"dependencies": {
"browser-sync": "^2.26.3",
"gulp": "^4.0.0",
"gulp-concat": "^2.6.1",
"gulp-csso": "^3.0.1",
"gulp-imagemin": "^5.0.3",
"gulp-plumber": "^1.2.1",
"gulp-sass": "^4.0.2",
"gulp-uglify": "^3.0.1"
}
}
ah okay
So it deploys on localhost 3000 but not 5000
so weird
Hello guys , can someone tell me what best frameworks for JavaScript and CSS?
Best is subjective. The most active is React, jQuery, Express and Angular.
Best for simplicity and power is VUE, most syntactically complicated is Angular, most widely used is React.
hey folks - i am using flask trying to setup some user signup, getting an issue when i import routes file into my main app
from flask import Flask, render_template
app = Flask(__name__)
#Routes
from user import routes
and routes file is just this
from flask import Flask
from app import app
from user.models import User
@app.route('/user/signup', methods=['GET'])
def signup():
return User().signup()
when i try to load /user/signup page i am getting 404
I'd say Svelte is the simplest (and probably the fastest out of all 4)
ooh a new one, it looks promising
so progress made... basically im able to host it at local host 3000
but it needs to be at 5000
in order for it to properly function on heroku
Can smb. help with Django DRF and password change?
Please also see: https://stackoverflow.com/questions/69561555/django-drf-unable-to-change-user-password-as-user-at-request-is-none
which makes no sense because in order for an application to work it needs to have a client facing ports of either 80 or 443.
when making a fullstack app, do yall usually start with the frontend or backend? Making a chat app and not sure if I should making my models, views first or start with basic react layout and build backend as I build out my react side?
Exactly what I was searching for.Thamks
Ground up, so backend first then work on incorporating client facing front end.
Thats how development teams work and thats how I choose to approach it but feel free to choose what you want
I was thinking the same, but i just started learning django and trying to build my frist relationship app (one-to-many) and its really hard for me to visualize it
like all the views I need and which ones
I don't know what you mean by views. Conceptual? or where to start or what
django views like do I need a get view for this page or a full crud view for another page blah balh
That tells me nothing
Like if I click chatroom ill need a GET view because it needs to grab all the messages from that chatroom model, but I'll need to probably delete messages too. So it's hard to visualize all the cases of views ill need without the frontend, but im new to django so im guessing its my current mindset
What I do is make the backend for each "component/part", and then the frontend
Or sometimes vice versa
So that it lets me visualize it, while still making sure both are being worked on
so you look at a component and then form the views youll need based on that component?
Yeah, pretty much
i really like that idea
Backend is what you do with the user data.
So take login information, security will be important. So when a user signs up or enters a password you want to store that information in a database. I recommend sqllite for your case at the moment. Import that data and store it then work on retrieval.
You can then build out the client facing backend Django and feed that information to your client facing front end html and css.
I made a diagram to help me visualize whats occuring which may help you.
I would take a step back and visualize what you want to do. Look at the broad concepts of the design. What do you want to do, then break it down into bite sized chunks of information.
Just replace flask with Django in the above diagram.
that was really nice of you to make that. thank you for explaining it. It seems like starting with backend is probably the best way. I might start with a hybrid tho rn just because I am overwhelmed with learning django and still feel lost at times (especially with relationships like one to many)
Well it's good that you're actually solving a problem because I guarantee you you aren't alone there. Once you get a web app up and running next it will be to determine what differentiates you aside from other applications.
how does css define discords window title?
even in the dev console it seems its title isnt changeable
afaik, that's defined through electron
Assuming you're talking about the desktop client
yeah im talking about the desktop client idek if the browser version has a "title"
im asking bc i know someone who uses betterdiscord and their theme is made with all css. and on top of that his title was different
it was like this
I have no idea how BD works
thanks for the help anyway 👍
how do i redirect to another page using Javascript
maybe window.location?
but it doesnt work
for me
you ain’t
Might be able to help
With your upcoming question
@low pasture you going to ask the question then?
maybe later
😑
i have a meld component and the flask's flash function does not work after successful registration, everything's fine and working and i think it's because of context issues but i don't know what else to do
class RegistrationForm(Component):
def save(self):
self.submitted = True
if self.validate():
form = self.form
#generate hashed password for the password
hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
user = User(
first_name=form.first_name.data,
last_name=form.last_name.data,
username=form.username.data,
email=form.email.data,
password=hashed_password
)
db.session.add(user)
db.session.commit()
flash('Your account has been created!', 'success')
return redirect(url_for('user.login'))
heres the template
{% extends "layout.html" %}
{% block title %}Register{% endblock %}
{% block content %}
{% meld "registration_form" %}
{% endblock %}
Does anyone here use or have experience with Pyramid?
I'm evaluating frameworks for an SPA backend. I've tried Django and Flask and they both have their ups and downs.
I only wish Django didn't so tightly couple the User model to the ORM. 
I've never used Pyramid, but can I just take a moment to promote FastAPI? It's really easy to use, but does things right.
Flask, very nice for small projects, easy to dig yourself into a hole of bad design.
I guess I hadn't considered FastAPI for this, it seemed very focused on well, APIs.
Isn't that what you'd typically want for an SPA?
Or did you have something else in mind?
you can customize the user model in django as well, does that not work for you?
no, that's it, I just didn't see anything aside from api key or oauth auth and we're stuck with SAML.
you should be able to use sso with django just fine
yeah, I have a working server rendered Django app.
some of this is driven from a cost prospective, it would be nice to not have to provision an rds instance just to handle django users.
fair
it looks like the sessions are extensible in that way, at least
because there's only maybe ~100 people in an org using this, i considered just using sqlite in the django docker container
oops, we redeployed? just recreate you on the next login or when we see your session
there's no other persistent data you'd need stored in a database though?
oh there's plenty, just those databases already exist
so this app is just going to be a middle man to make calls to other apps?
pretty much
I see
i'd hope whoever has to touch it after me would find django easier than whatever homebrew we came up with
but I'll check out FastAPI too
fastapi does seem pretty cool
also the sqlmodel orm wrapper around sqlalchemy that the same guy made
typehints to define db columns? :mindblown:

Build a discord-like application with Python Django. Visit the finished application at https://studybuddev.herokuapp.com/
Get The Full Django Beginners Course:
https://dennisivy.teachable.com/p/django-beginners-course/?product_id=3222835&coupon_code=BRAD
Use promo code BRAD for 50% off
Dennis Ivy YouTube Channel:
https://www.youtube.com/c/den...
ok thank
@eternal blade hey
i am working with signals.py when im adding any post from my admin panel without adding img it renders it by signals.py (that's what i want ) but when i am not selecting img and adding post (from frontend)
it's adding post to db
but when i open post it throws error
ValueError at /notes/6/
The 'thumbnail' attribute has no file associated with it.```
so ig models are correct as it's working from db
problem is in my views or my html
one thing that i noticed more is when i add from admin panel it adds default.jpeg automatically , but when i add post from frontend it leaves that field empty
Hey, I am making a Django application with opencv. I am using Websockets to establish a real time connection between Python and JS. What I need help with is to send Images from python to JS in real time. I tried encoding image and sending but the decoding is not working properly. Can anyone provide a basic code snippet for Python (image encoding) and JavaScript (decoding)?
my next message is propbably going to get me banned
Then... don't send it?
Just use HTML/CSS/JS instead
oh wait im still alive
this was unexpected, thank you
I'm trying to change my users password using Django REST Framework (DRF) but I only get back a faulty response and I don't understand why, please have a look at my code.
models.py
class User(
since you have a serializer with fields password2 and old_password with model=get_user_model
the serializer is trying to save user.password2 and user.old_password
which aren't actually fields.
I've never used a serializer for change password form, I'm not sure if this is a good use of them
I would just use django forms
it might be possible to set required=False on password2 and old_password but still validate them normally and then in your validate method, right before you return attrs, do attrs.pop('password2') and attrs.pop(old_password)
because you don't actually want the serializer to try to save those onto your model
hey, How can i place images under each other? i wanna place "arsenal" and "westham" right under "manchester city" and "liverpool"
guys i have a weird css problem can someone help
overflow:clip is not working with images but only on phones
it works on pc even when i scale it the same size as a phone
how it should look
how it looks only on phones
CAN SOMEONE HELP ??
PLS
if i'm using s3 buckets for user file upload, how big of a deal is setting the bucket to be public? i feel like aws is really trying to discourage me from doing that
actually let's not xyz around the problem, what i'm trying to do is set up uploaded files' urls to never expire, which seems to happen because of query string authentication (i think)
hello, i have a python program to do but im biig noob, can someone help me ?
So I got base64. Where do I put it in JavaScript?
does anyone know how to log out a user who was logged in using google authlib
im using flask and flask_login
when i go to current_user
it shows the account that i logged into like way back from
even if i log out
the logout_user() works
but when i login using another google account
it still shows the same one
i have literaly no idea how to work with javascript but i posted code, As for maybe it could help
I have already searched on 100 websites. Thanks anyway.
I did what your talking about but used vnc and got the framebuffer data. sounds like you're trying to do it with screen shots. but the canvas code in my example should show you how to unpack pixel data from a websocket... https://github.com/byteface/vnc2browser/
Unpacking the pixel data? You mean I take the image numpy array and place each pixel to form an image?
we should go back to your original question i guess.
if it's just 1 image
save the image. on disk. the load it from teh server the way you would any image
Not one image. Its like video streaming. So I process each frame and send it via channels.
you may need ffmpeg and not going to get a quick answer then depending on your needs as there will be things to learn
Please post the question
Let me look into that
on the html side i guess a video tag can cope. setting up the stream will be the hard part.
you should not deleteusers
you should instead send a DELETE request to users
GET POST DELETE UPDATE is same as crud
ah
so what should I write in the
sql
it doesn't recongnize delete as it do for get/post
hmmm. u can do it easier.
dont try to code it
get an example that works. and start back to learning REST
you have 1 endpoint
/users
you can GET
to read info
POST to put info
DELETE to remove it
flask will have many REST API plugins. that set this up for you
and you may not have to do any sql. as the model will update based on the request type
i.e EVE is very good and can be done by configuration. but better for very static datasets
flask-restful was anothter. and paired with marshmallow will save you a lot of serialisaiton
Streaming is a hard part. I am still thinking to encode image into string and vice versa.
hey
hello mortal
what is suggested using media url or static to store imgs. in Django
does they matter?
Use Static
I think it loads faster in browser
ohh
I think you use media url for user uploaded files, and static for assets that are part of your website design
how can i set rows of a textarea using django forms textarea widget
could be wrong I'm not too familiar with django
ok
The error is that the req object(NoneType) is not subscriptable. This is because request.json is a method not an attribute. The correct code should be
req=request.json()
or
req = requests.json()
some one help with this. It is Important
this is correct
or, more generally
any file that won't change without redeployment
thats clear now
shrugs
Thanx
honestly
most "REST" APIs aren't really RESTful
in particular, when you have deeply nested data, a RESTful style can be complicated to do efficiently
Hi everyone. I'm trying to implement a feedback form on my Django error pages. Currently I've setup a custom 500 handler which I'm pointing to, but when I trying a 500 error, I need a function to give me the latest error log event id (I'm using sentry.io for those who are curious). But the custom 500 view is never triggered when responding with the 500 page, so I cannot inject the even_id as data into the template
anyone any experience with this?
Also, regarding what someone said about a delete request: I believe you cannot make a delete request from the browser without JS
Hey folks,
I'm new to DRF (Django REST Framework) and just have setup my first usable POST endpoint, please see my code to create a new User object using POST:
@api_view(['POST'])
@permission_classes([AllowAny])
def user_create(request):
if request.method == 'POST':
serializer = CreateUserSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
serializer.save()
return JsonResponse(serializer.data, safe=False)
class CreateUserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ('user', 'password')
extra_kwargs = {'password': {'write_only': True}} # We don't want to show the hashed password
def create(self, validated_data):
password = validated_data.pop('password')
user = User.objects.create_user(
validated_data['user'],
)
user.set_password(password)
user.save()
return user
So far so good. If I now want to create a User Object using POST it works fine for the first time. But if I send the same request twice, the second request just returns "Bad Request". Well that also makes sense as the User object is already existing.
It would be awesome if I would be able to catch this behavior somehow and return a message instead of a Bad Request.
Thanks in advanced
which REST api isn't restful?. you have an example of one of these data structures? (that isn't a json blob in the db)
for the latter: not the data structure itself
but say your frontend wants a domain object
that involves several joins
okay
for example
you have an Album model
an Album has an M2M relationship with a Track
a Track has an M2M relationship with an Artist
in some cases, you want the Album with the full representations of its Tracks and Artists
in others, you don't
this is difficult to model RESTfully
as for your other point
one of the big things about REST
is HATEOAS
I very rarely see any sort of discoverability in a purportedly RESTful API
much more likely is
some sort of external spec (like OpenAPI)
i was about to say HATEOAS
but yes. people don't implement it. which is why eve was nice
how ever
couchdb invented a http interface
which mongo nicked and then put mongo query language on top
writing off the need to do apis for json dbs
as you can do REST direct to the db
my point being for that persons issue. is with a hello world flask restful. they wouldn't be even having that problem. they are at the delete user step
which is probably paragraph 3 on the intro docs
shrugs
that's fair
ye. to your point. in eve they were called 'projections' and joined records were configured by an exlude or include rule in the query. hence using a lib rather than trying to code your own is often better. as it acutally just does it for you and is easier.
I don't deny that
not sure what Flask has for this
but
DRF does it p well
So I'm new to Docker but not Django, and sometimes when I don't like the server I move it (manually), should I use Docker to deploy my django website?
do you guys use flask or a framwork like django?
how do you filter by object not in m2m?
like the opposite of Chat.objects.filter(members=user) where members is m2m field in Chat model
i just had to exclude instead lol
how do you add an object to m2m field to all objects (of other model) in queryset?
like below but with queryset
obj = MyModel.objects.get(pk=1)
obj.my_m2m_field.add(some_object)
document.querySelector(".btn-wrap").addEventListener(
"click",
(e) => {
if (!e.target.matches("button, button img")) return;
const btn =
e.target.tagName === "BUTTON" ? e.target : e.target.parentElement;
game.buttonFunctions[btn.dataset.func]();
},
{ passive: true }
);
what does that code do


django?
dj bravo
no no its dj bravo
??
You are java man lg
not rlly
what does that code do
Hello, is there a way to set a default permission_classes for every view in django-rest-framework?
Yes in setting.py
Thanks
How can I exclude the permissions from certain views?
nvm found it, thanks
Suggest a library that takes a PNG photo from an HTML file
you should create a validate_user method and check if the user already exists.
if it does exist, you need to do raise serializers.ValidationError('This user already exists')
Make a base permission then override it
The better way is to make permission.py and import permission from their
Hey guys! Probably someone can help me!
How can I make a migrations if I wrote models not in models.py?
Follow me in the answer
What is the best way to use for scraping 2000 URL addresses?
Quick question,
Why Am I getting the error name 'SERVER' is not defined
My View:
class RobotDetail(UpdateView):
model = models.Robot
form_class = RobotUpdateForm
template_name = 'dashboard-home/robotdetail.html'
robo = Robot.objects.get(pk=pk)
PORT = robo.port
SERVER = robo.server
My Model:
port = models.IntegerField()
server = models.CharField(max_length=200, default='10.10.19', blank=True, null=True)
Plz Ping When Replying
is it possible for python to interface with html?
how can i create a google forms like application
by django
where ppl can share link by creating there form and there will be mcq's
designed by the link sharing (admin/host of the form)
and it will contain responses same as google forms
@eternal blade
how to write a mock api? eg I want to mock an api my program relies on for testing
any recommended libraries to best do that?
I want to have minimal dependencies, but also easiest to write
sorry, bit busy right now
no, i want to mock the actual api they use
so I'll make requests to a test server which doesn't do anything
may i ask what is does it mean when i do as following ```
def function(variable: int = 0):
def function(variable:int =0) => list:
You mean type hints?
yea
It tells you that the function expects an int and returns a list.
ohhh