#web-development
2 messages ยท Page 160 of 1
where
sec
Hey @quasi relic!
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:
oh, you're using wtforms,
yes
i've tried to use it to upload, but i never got it to work
Hey @quasi relic!
It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.
Feel free to ask in #community-meta if you think this is a mistake.
paste the text, the bot will automatically remove it
Anyways what I was going to say was that make sure you have the enctype as multipart/form-data to post files through a form.
I am getting the error TypeError: unhashable type: 'dict' and this is my code:
@app.post("/novels")
def add_novel(novel_data: Novel):
new_novel = {
"title": novel_data.title,
"author": novel_data.author,
"synopsis": novel_data.synopsis,
"accepted": novel_data.accepted,
}
novels_collection.insert_one({new_novel})
return {"data": new_novel}
When i try to just novels_collection.insert_one({novel_data}) it gives me a similar error TypeError: unhashable type: 'Novel' (this is using fastapi and pymongo)
oh ye it worked thanks, so what does it mean, what does it do?
{} is being treated like a set, because you already new_novel being a dictionary, so you're just trying to insert a dict into a set which cant be done
Itโs just how you encode data that will be sent, and so allows files like that to be sent.
alright thanks so much ๐
oh i see, thanks but how do i make {} not being treated like a set? do i just
novels_collection.insert_one({"novel": new_novel})
? or is there another way? (my brain has a hard time computing today and in general so sorry if this question seems stupid)
well, its already a dict
if you want it to litterally have those keys and columns as is in the db
just give it the var
if you want it to be stored like:
{
"novel": {
# ... Stuff
}
}
``` then use the `{"novel": new_novel}`
otherwise
just `new_novel` will produce:
```py
{
"title": stuff,
# ... etc...
}```
Hi,
I'm building a content aggregator app which will scrape the data from some websites and present those data (after doing some formatting) to the frontend. I'm looking for some suggestions , references on the python framework etc. to use.
oh okay, thanks a lot for your help and time! i really appreciate it
Webcrawler framework https://scrapy.org/
and for the server, there are plenty of options
What is the difference between Django socket.io and Django channels?
what to use when?
is it possible to change the maximum characters required to enter for django.contrib.auth signup password (which is 8)?
Hey there, I was hoping to get some clarfication. I have been working with Flask for a few months now, and think it is awesome. I love the factory design principle that can be used, and blueprints. Also super excited about Flask 2.0 and the nested blueprints that are now available. I have always created monlithic apllications, and only really got introduced to the concept of Microservices recently. But as I was working through the concept, I was not clear how Micoservices would really be a change from just using Blueprints. Are they pratically doing the same thing? Or there advantages to using various microservices with or without blueprints?
uhhh, use the django form i guess?
@buoyant shuttle hey
Hey @twin hamlet!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Sup
See
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
!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.
So we can see
Link?
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.
Paste the code to both views and url
Can I add def to <button> in flask ?
from flask import Flask, render_template_string
app = Flask(__name__)
def test():
print("test")
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template_string('''
<button>click me</button>
''')
if __name__ == '__main__':
app.run(debug=True)
How I add function to Button ?
403, literally status means u cant access the content in that url
the server is stopping u
The HTTP 403 is a HTTP status code meaning access to the requested resource is forbidden. The server understood the request, but will not fulfill it.
it means the server got your request, but would not give u the ideal content
Hi guys, I'm kinda new to css
thats javascript stuff
I know the basics, but I was wondering when should I get into bootstrap??
you can stry to add a script tag, and run your js there
bootstrap is a framework, basically if you dont want to make your own stuff
Yeah, I'm having a hard time making the websites I kinda pictured in my head
and I tried bootstrap but I didn't understand the "container" classes and all that
container is like a box, or someting just a div that expands. you can make it with pure html and css
So basically a responsive section of the site?
do you know javascript?
just as the name suggest
plain container
nope
i suggest u learn js,
Getting started with flask in pycharm. I'm pretty sure my server is still running in the background after closing pycharm but I can't find what I should kill in the windows task manager... Is this common? Also is there a name for the default "server" back end of flask?
does going to localhost produce anything?
http://127.0.0.1:5000/ returns "index page" (as a test)
this could be true
so yeah
kill the process running on your server lol
hmm, are you on windows?
killed all python apps so not sure what to kill next
also never start server in pycharm use cmd/terminal
if so it's probably a python process
Yep and most google answers are for linux...
i mean using cmd commands
Why?
it runs on port 5000
right click taskbar > task manager
cause u cabn close pycharm and the server is still running lol
kill port 5000, and it stops the process running on that port
that did the trick, looks like I missed a python to kill, thanks !
so in order to test run a flask project I should run it outside of pycharm? Doesn't pycharm know how to handle flask projects and close it?
Im not saying that its bad, but i have that habit that pycharm would do it for me. So i run the server in command line, seperate
alright will keep it in mind ๐ that background server also explains why I couldn't see the changes when running the script....
np
As someone who keeps trying to learn Javascript but my own biases against it keep getting in the way, and I already know Python pretty well, is there a recommend tech stack for web development that minimizes the amount of JS I have to write?
Anyone on with experience integrating PostgreSQL using psycopg2 into base flask for an API? I have some questions regarding best practices for integration, I'm used to SQLAlchemy so I'm eager to try to find cleanliness/DRY shortcuts for the code rather than bloating
Is there anything wrong with having one handler function and having a series of if statements for method eg if request.method == 'PUT': as an example?
Yeah it can get bloated, and hard to read or maintain
Each route should be doing a specific thing to a resource.
For your database functions, you might want to have a data layer and this way if you ever do have to change the implementation its easier to do so, without affecting other parts of your code.
Honestly, the recommended tech stack a lot of the time now involves a frontend that uses JS and a lot of it.
You can get away with using a templating engine. This does depend on the complexity of the project/site.
How best do I go about doing this? I'm in the midst of figuring it out but I'm not sure how I'd abstract the methods for writing/reading etc from DB without purpose building each function
Create a crud.py file in the same package. There you can create simple functions to read, update, delete, etc. Also there is absolutely nothing wrong with using if statements to delegate a request based on request methods.
I would recommend not having all of your logic in a route though. If you find you're doing that a lot. Create a utils.py file in the same module and create the logic there. If you find you're repeating something a lot and need the utils used across blueprints, move it out of the "app".
Hey, should I go for django or flask for learning web dev & execute my own idea?
It seems as if django has more data, so it would be better to learn
That really shouldn't be used unless you have some really specific reason...
Whats the idea and the requirements of the project, or end goal
hmmm?
As a webserver
yeah. I don't see the problem
Why would you want to use it for a server?
django doesn't look into the "templates" folder under my app
I've added my app in INSTALLED_APPS and APP_DIRS is set to True
You'll have to create everything basically from scratch? ๐
I mean you definitely do but to each their own
for templates there's jinja
But there also is not much out there based on. This includes packages, tutorials, probably even stuff on stackoverflow. If you run into a big problem you're probably on your own.
I would guess it would be.
If you need an async option there are actual frameworks out there.
Seems to be some miss-conception of stuff
aiohttp is fine with it's inbuilt webserver
its production ready, e.g. it's the same standard of gunicorn, uvicorn, hypercorn etc...
Sure, it's fine.
What you shouldnt do still though is expose it without a reverse proxy really
There is downsides as I pointed out.
Aiohttp has a bunch of stuff
it's not exactly a under-supported library
being the largest and most used async http library around
I still recommend putting the server behind something like Nginx because it protects you from all sorts of nasty and also allows for things like HTTP/2 which can boost performance
A reverse proxy does *not *boost performance in most cases. Using it though is highly recommended though due to the security benefits.
In Pythons world it can, although typically not many people will actually make use of the the extra wiggle room it gives
HTTP/2 from client to proxy does add significant benefit though in terms amount of connections the proxy can handle vs the amount of requests it can process
That is very very unlikely even in Python. The important part is using something such as gunicorn or uvicorn
due to the single connection multi-plexing
Right, but a reverse proxy can only handle so much traffic itself. For example, look at something such as Kestrel.
yeah, although that number will be significantly higher than anything you write 
Unlikely ๐
not really
Proxies are very simple setups in terms of CPU time
by the time you have to add your database logic etc...
hi guys, im learnining django-rest and i need a bit of help
your application behind it will take considerably longer
Things like Nginx and Apache have also got decades of optimizations behind them 
Yes, but that doesn't mean it makes your server faster.
In most cases the raw execution speed is faster
Think that another reason for reverse proxy was that you can run many aiohtttp instances
you can do that anyway
all python webservers rely on the pre-forking web server model to function properly
If you're going to be scaling horizontally absolutely it's needed. It should always be used.
But saying it's faster ๐คฆโโ๏ธ
well, that's what the docs said idk
Instances could mean multiple things. You're not wrong you're good.
I mean the docs do say it
Just call aiohttp.web.run_app() function passing aiohttp.web.Application instance.
The method is very simple and could be the best solution in some trivial cases. But it does not utilize all CPU cores.
For running multiple aiohttp server instances use reverse proxies.
No idea why though
I imagine it's referring to the fact that it's process management will be better than anything you setup in all likely hood
Instances could be related to being instances spread across servers.
Or it could be if you had two instances running on the same server performing different tasks.
Nah, context for this is referring to a process
Mostly from aiohttp's perspective it's referring to not being able to fully use the CPU
You would use uvicorn if you wanted to create more instances of the application.
well, you'd use gunicorn because it has better process management
With an async server?
Yes. If you read the uvicorn docs it recommends you use gunicorn with the uvicorn worker rather than uvicorn just by itself
That's still using uvicorn though?
Bruh
Im talking in terms of the main controller not the workers
Ask the question
Okay, well regardless of all that. Why would you want to make a server with aiohttp over fastapi, django, flask, etc?
Well generally, its lightweight and has reasonable performance / good performance in comparison to the others, Eco system tools are also reasonably solid, most ASGI setups are compatible with aiohttp anyway.
The single process server is also possible the nicest thing in the world to deal with when deploying at scale vs dealing with blobs of gunicorn instances
Makes me wish there were more servers that supported a no-watcher process mode
im getting this error when creating a superuser from a custom model user
TypeError: create_user() missing 3 required positional arguments: 'rut', 'first_name', and 'last_name'
and now im trying to find something so the superuser just require email and password, can it be done? or do i need to make another usermodel or something
Do you have a user manager or an object manager?
yes (im following a guide)
"""
Create and save a SuperUser with the given email and password.
"""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError(_('Superuser must have is_staff=True.'))
if extra_fields.get('is_superuser') is not True:
raise ValueError(_('Superuser must have is_superuser=True.'))
return self.create_user(email, password, **extra_fields)
Is there a noticeable performance difference? If so do you happen to have benchmarks or reference for it with the code? (Genuinely curious).
Generally no real performance difference in the real world in comparison to other ASGI frameworks
Why use it over something with a bigger community? Besides gunicorn I see very little reason. Unless you're making a very small project
It doesnt really have any smaller community compared to other setups
not in the ASGI world
like i said
aiohttp is the biggest async http libary in python
For the request aspect, yes I can understand that it doesn't. (Does have a decent sized community)
but I have not yet seen or heard of anyone using it in production for a server
People use, probably more than things like starlette or quart tbh
Can you share the user model?
Right. Which is why I was saying that you probably shouldn't use it unless you have a very specific use case or reason. It would make more sense (at least to me) to go with something that has a bigger community and more information available.
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
email = models.EmailField(_('email address'), unique=True)
user_type = models.CharField(max_length=20)
rut = models.CharField(max_length=20)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email```
generally it's a pretty solid choice if you want to go with the asyncio route
You need to provide those three required fields when creating the user model through the cli.
ok, then if i want to not use the fields can i make another custom user only for the superuser?
Well, the more you know I guess.
Uhh, no don't do that please. Make the field not required. You should keep a single user model as that's how Django was created to be used.
null=True, blank=True on the fields. Or, you can provide a default value default='something'
yeah but that make the fields not required when making a user account right? in that case i should make them required on the frontend or smt
That is right.
You should be validating user input with a serializer though. You can specify that the field is required on there.
okk, i didnt know that, im still making the models, serializers is that comes next thanks!
No worries. You can also update the UserManager to require the fields. If you're new to drf you might have a bit of a harder time figuring out how to override the serializer.ModelSerializer if you're inheriting from it.
oh yeah i got one method "create_user" that ask for values of the fields
ohhhh right, because when i user manage.py createsuperuser i got the error, so if i update the create_superuser it should ask me for the fields when i createsuperuser (?)
You'll have to test that one since it's been a while for me
You can always test if it exists in the extra field, or provide a default value for a extra_field
ok i think i get it, thank you very much
No problem! Best of luck
Does anyone know if there is a way to scrape fb data
But ppl say scraping fb isn't legal n stuff
do you know html?
Yep
hmmm okay
FB is probably going to give some problems
with authentication
and the likes
So maybe use selenium instead
credentials = {"email":"your_email", "pass":"your_password"}
login_basic_url = 'https://mbasic.facebook.com/login'
def parse_html(url):
with requests.Session() as session:
post = session.post(login_basic_url, data=credentials)
parsed_html = session.get(url)
print(parsed_html)
return parsed_html
parse_html(url)
See this... I did this.... Gives 505 error
sorry, I don't know how FB auth works
In the credentual part u just put in ur email n password
The authentication gets done
Also u need to explicitly male a url variable with the link to the post u wanna scrape
how do I do an external request in flask? etc:
headers = {
"rbx-authentication-ticket": csrftoken
}
requests.post('https://auth.roblox.com/v1/authentication-ticket/redeem, headers=headers)```
but within a flask app.route endpoint
Hi, I'm using FastAPI and trying out Form rn, it forces you to provide a default value, but I don't want that, I just want it to return an error when the Form field is not found, is there a way for that? Or will I have to use Form(None) and check for NoneType myself?
Something like this:
@app.put("/user/new", response_class=ORJSONResponse, response_model=UserBase)
def user_new(username: str = Form(None), password: str = Form(None)):
if not (username and password and len(username) > 2 and len(password) > 4):
raise HTTPException(status.HTTP_400_BAD_REQUEST)
this has to be a joke.
please don't do that ever running a web app with root is a massive security risk
any bug in the app will give users probably the access to the server with root privileges.
I know no one uses flask for publishing but I won't trust using this even at the localhost
since any testing and modifying to the database will maybe make your database files locked
with root only can edit to them.
On top of that, if someone is asking a question like that they must not know a ton about Flask or whatnot.
Yes I agree. Flask is mainly used for web apps and doing that with knowing that it's for web apps can't be real.
Heyo, I'm trying to set up a Quart website along with an attached API at the /api endpoint. I've looked at the quart-openapi extension but I'm not sure if using the Pint from there means the entire website is works under the docs methods there and whatnot or if I can just designated a specific endpoint for it like with flask_restful. Not sure if I'm making sense, but any help would be much appreciated!
I'm wondering if I should just use normal Quart and make my own endpoints since it's just fetching data based on URL query args
sorry couldn't answer your question but do you know if django accepts new requests in parallel without having to resort to async?
No worries, never used django so can't help either ๐ฆ
You as well ๐
How can I make a multi page layout for my website?
I want it so when you click stuff in the navbar it prings you down
what do you mean pring?
if you want to link a url you can use <a href="link></a> or js
I guess he meant bring
oh
<div onclick="window.location.href = link;"></div>
could be used too
Are Django rest framework applications vulnerable to XSS and SQL injection attacks?
Would i talk about selenium here?
it depends on your choice of its usage
parallel execution of multiple tabs or windows with different links
https://docs.djangoproject.com/en/3.2/topics/security/
protected if you setup it right
for which sort of task?
well, there is #async-and-concurrency channel which can help more about parallelism
selenium is quite webby, so here is approriate too
well, im just trying to execute code on 12 different websites all at the same time
and i havnt found a thing on it
https://stackoverflow.com/questions/42732958/python-parallel-execution-with-selenium
There are links to even github project which makes it
https://github.com/testlabauto/local_selenium_pool
Additionally those testing tutorials can be checked
since selenium is needed for paralled runnin in them
https://www.lambdatest.com/blog/pytest-tutorial-parallel-testing-with-selenium-grid/
https://www.browserstack.com/docs/automate/selenium/getting-started/python/run-tests-in-parallel
Further googling is available with "selenium parallel execution python"
thanks for the reply, although ive actually have seen all of these before, i just dont understand them completely i didnt know if they fit my objective. i will look into them further
I am trying to fit my API into having nice best practices REST logic
I have actions
customer register -> /customer [POST]
customer login -> what is it best url path for this? -> /customer/login [POST] -> perhaps this, since it created token for authentification
customer data -> ...? I would prefer having JSON payload, but GET request I think is not supporting it, I could fit into query parameter though -> /customer [GET]
customer update -> /customer [PUT]
customer send verify email -> API url: /customer/email [POST]
customer verify email -> API url: /customer/email [PUT]
well, probably above URLs will fit me better than what I did before
how to encode a python dictionary into a URL variable? Example: {"id":"12345","first":16} => %7B%22id%22%3A%2212345%22%2C%22first%22%3A16%7d
Hello
I'm facing issues at replication of urls.py means of app (include) in django
And i can't get docs can anyone tell me the way to get more output from docs I'm new at it and django doc's are soo much vast
what are the stuff i need to learn in networking so i can start with webdev backend and djangoo specifically
For dev you don't need much
you just need to point your browser at localhost on the port django is configured to use
One of my college tutors has said that when classes start up in September we're gonna be doing C# ASP for web backend because it's industry standard. I kinda don't wanna do that cos I already know Django.
Is it viable to go for a full stack career with Django as my backend system?
ะััั ััััะบะธะต?
Tried this before posting here, I seem to have some problem with urllib module cause when I tried to pip install it, it didn't work later I was able to install it by specifying a version but now it would give me this error: tud = urllib.parse.urlencode( AttributeError: module 'urllib' has no attribute 'parse'
urllib.parse.urlencode("VARIABLE")```
i know less than you sorry maybe someone more knowledgable can help
How do I send http response with image to client? Should I put the image bytes into the http response content like this?
HTTP/1.1 200 OK
Content-Type: image/png
{ Image data }
can anyone provide me some resources for django restfull api
I'm getting a weird behavior. In the following code the first print is "True" but still the second print is never fired. Any ideas why?
response = json.loads(request.body)
print(response.get("newlikestatus"))
if response.get("newlikestatus") is True:
print("Is true")
what framework you using?
I'm making my own
visit the main django rest framework docs
any modules?
only socket
visit #networks
thanks ni
Everything is vulnerable if used wrong
and you should never rely solely on a framework for security.
im vulnerable even when im used correctly ๐ฅ
๐ค
what is the modern equivalent of get_profile() in django
does anyone have any recommendations for css frameworks outside of bootstrap?
is there a way to set a form data field as mandatory in FastAPI? it forces me to set a default value, which is not what I want, i just want the request to fail if the form data field is not there.
Anyone know the name of the artist?
@shy hatch have you browsed this page for a solution? https://fastapi.tiangolo.com/tutorial/body-fields/
FastAPI framework, high performance, easy to learn, fast to code, ready for production
I added the management command(basecommand). I give the file name as the command entry I added(I'm using is an Excel file). I want to open files with pandas and save line by line information to the model. I want to ask if I'm on the right track. Does it get the data properly? I'm going to send the excel file and source code. Can you help this topic?
from django.db import models
from django.utils.translation import gettext_lazy as _
# Create your models here.
class PaidDrugsUpdates(models.Model):
class worksheet_type(models.IntegerChoices):
ADDED = 0, _('Eklenenler')
EDITED = 1, _('Dรผzenlenenler')
EXTRACTED = 2, _('รฤฑkarฤฑlanlar')
worksheet = models.IntegerField(choices=worksheet_type.choices)
public_code = models.CharField("ฤฐlaรง Adฤฑ", max_length=6)
barcode = models.CharField("Barkod", max_length=13)
name = models.CharField("ฤฐlaรง Adฤฑ", max_length=250)
old_barcode1 = models.CharField("Eski Barkod-1",max_length=13)
old_barcode2 = models.CharField("Eski Barkod-2",max_length=13)
e_code = models.CharField("Eลdeฤer(Benzer) รrรผn Grubu",max_length=5)
reference_price_group = models.CharField("Referans Fiyat Grubu",max_length=7)
list_entry_date = models.DateField("Listeye Giriล Tarihi")
activation_date = models.DateField("Aktiflenme Tarihi")
passive_date = models.DateField("Pasiflenme Tarihi")
generic_distribution = models.CharField("Orijinal/Jenerik/Yirmi Yฤฑl",max_length=12)
high_sales_price = models.CharField("Depocuya Satฤฑล Fiyatฤฑ 23,81 TL ve รผzeri ise",max_length=10)
medium_sales_price = models.CharField("Depocuya Satฤฑล Fiyatฤฑ 15,81 TL(dahil) ile 23,80 TL(dahil) arasฤฑnda ise",max_length=10)
normal_sales_price = models.CharField("Depocuya Satฤฑล Fiyatฤฑ 8,26 TL(dahil) ile 15,80 TL(dahil) arasฤฑnda ise",max_length=10)
small_sales_price = models.CharField("Depocuya Satฤฑล Fiyatฤฑ 8,25 TL ve altฤฑnda ise",max_length=10)
special_discount = models.CharField("รzel ฤฐskonto",max_length=10)
pharmacist_discount_rate = models.CharField("Eczacฤฑ ฤฐndirim Oranฤฑ",max_length=10)
band_calculation_date = models.CharField("Band Hesabฤฑ Takibinin Baลlangฤฑรง Tarihi",max_length=10)
distribution_document_date = models.DateField("Firma tarafฤฑndan Daฤฤฑtฤฑm Belgesinin Bildirileceฤi Son Tarihi")
https://pastebin.ubuntu.com/p/skBZCKXqpH/ and this is management codes for updates
https://prnt.sc/13im52i and this is the excel file screenshot
thank you! i'll have a read!
i thought those ... were something i had to fill in myself haha
I'm trying to format a date created by the django API
render() {
const { blogList } = this.state;
return (
<context.Consumer>
{({ a, getFormatDate }) => (
<section className="blog-list">
<h1>Blogs {this.state.a} </h1>
{blogList.map((blog) => (
<article className="blog" key={blog.id}>
<h2>{blog.title}</h2>
<hr />
<div className="blog-body">{blog.body}</div>
<p className="blog-author">{blog.author}</p>
<span className="blog-date">{getFormatDate(blog.date)}</span>
</article>
))}
</section>
)}
</context.Consumer>
);
}```
In my component
this is the function I am using ```jsx
getFormatDate = (date) => {
console.log(date);
return new Intl.DateTimeFormat("en-GB", {
dateStyle: "full",
timeStyle: "short",
}).format(date);
};
But I get this error when the component is rendered.
RangeError: Invalid time value
this is an example of what kind of time values are passed to the function 2021-05-26T19:57:47.353005Z
maybe like this?
new Intl.DateTimeFormat("en-GB", {
dateStyle: "full",
timeStyle: "short",
}).format(new Date("2021-05-26T19:57:47.353005Z"))```
Anyone know about django here ?
bet. what's your question
yep
who does graphql with the flask?
yesss It worked
render() {
const { blogList } = this.state;
return (
<context.Consumer>
{({ a, getFormatDate }) => (
<section className="blog-list">
<h1>Blogs {a} </h1>
{blogList.map((blog) => (
<article className="blog" key={blog.id}>
<h2>{blog.title}</h2>
<hr />
<div className="blog-body">{blog.body}</div>
<p className="blog-author">{blog.author}</p>
<span className="blog-date">{getFormatDate(blog.date)}</span>
</article>
))}
</section>
)}
</context.Consumer>
);
}```
So here in my render mehtod
in the article block in the p element I am rendering the author
the author is a user model in my django API
a customUser
I want these checkboxes in front of the name like for e.g in front of NAME : Narayan Kohli
I want to render the name of the author and not the id
can someone help me in #help-potato
awesome!
are there any methods of getting the file size in bytes from FastAPI's UploadFile? or do we have to write the data to another temporary file and use that to determine file size?
hello there, hope everybody is having a good day.
new to programming. just started learning python a month ago.
trying to understand json files and accessing them through python
if i wanted to update a json file,
i was wondering if there was a way to append to it directly instead of having to re-write the whole file?
import json
# currently I understand that i first need to
# load the information on the json file as a variable
with open("test.json") as json_file:
jf_var = json.load(json_file)
# and when i want to add information on to it,
# i add it the variable.
jf_var["feb"] = "february"
jf_var["mar"] = "march"
# but when i write it, to the json file,
# i feel like there is a more efficient way
# intsead of just re-writing the entire file
with open("test.json", "w") as json_file:
json.dump(jf_var, json_file, indent=4)
# is there a way to just kind of append to the json file maybe?
https://stackoverflow.com/questions/12994442/how-to-append-data-to-a-json-file
json objects have a syntax that means the whole object must be read and parsed in order to understand any part of it
Hence there's no way to append data not already in a file. If this part is not taking up too much time, just stick with it. Otherwise there are a couple of other options you can look into for storing data!
i see. thank you
Has anyone worked with the Docusign api before? I am having issues with getting the auth to work ๐ฅ
is it a good idea to reactify django?
Anyone know about django here ?
seems more like HTML / template issue; code of template would be helpful ๐
the way jinja inheritance works is something like this
<!DOCTYPE html>
<html lang="en">
<head>
{% block head %} {% endblock %}
</head>
<body>
{% block content %} {% endblock %}
</body>
</html>
{% extends "snippetAbove.html" %}
{% block head %} head {% endblock %}
{% block head %} content {% endblock %}
instead of this, is there a way to fill the blocks from one parent with multiple files?
<!DOCTYPE html>
<html lang="en">
<head>
{% block from "head.txt" %} {% endblock %}
</head>
<body>
{% block from "content.txt" %} {% endblock %}
</body>
</html>
you mean something like include? https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#include

tysm
I need help with async views in django. I get this error when I try to access my async view: ValueError: The view emailbot_dashboard.views.exclude didn't return an HttpResponse object. It returned an unawaited coroutine instead. You may need to add an 'await' into your view.
async def exclude(request):
try:
guild = request.session['select_guild']
except KeyError:
return HttpResponseRedirect('guild')
guild = 762450334513365002
if guild:
data = {"guild":guild[1]}
excluded_channels = await get_excluded_channels(data)
channel_names = [channel.channel_name for channel in excluded_channels]
excluded_channel_form = ExcludedChannels(channel_names, True)
return render(request,"Excluded.html", {"chosen_guild": guild[0], "form":excluded_channel_form})```
@stable hemlock you need to add the async keyword into your route method
in flask its: but I could be wrong since i'm learning how to use async myself ๐
@app.route('/async/<something>')
async def my_async_request(something):
my_async_response = await exclude(something)
return my_async_response
which cms to use for django?
There is not a decorator like that in Django.
try return await render(request,"Excluded.html", {"chosen_guild": guild[0], "form":excluded_channel_form})
Ok.
Does anyone know which version of Flask is NOT multi-threaded?
so did it work?
nevermind. app.run(port=8080, threaded=False) multithreading appears to be available since 0.12.5
I am not at my computer at the moment. Will try later.
form = UserCreationForm()
if request.method == 'POST':
regForm = UserCreationForm(request.POST)
if regForm.is_valid():
regForm.save()
return redirect('login')
else:
for msg in form.error_messages:
messages.error(request, f"{msg}: {form.error_messages[msg]}")
print(msg)
return render(request, 'registration/register.html', {'form':form})```
so for some reason this line of code will always print me the following message on screen "password_mismatch: The two password fields didnโt match.", even tho the passwords match but the problem could be for example, password hasnt met the min_lenght, it will still print the above message, any solutions to this?
I assume messages.error... and print(msg) is all correctly indented in your code?
form.error_messages should be regForm.error_messages right?
Can you share UserCreationForm?
how
Oh I meant like copy and paste the code for that form on here? If it's too big a pastebin of it would be great.
Ah I see. Can you share what you have in your template?
this is what i could find on django docs of it
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
error_messages = {
'password_mismatch': _("The two password fields didn't match."),
}
password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
widget=forms.PasswordInput,
help_text=_("Enter the same password as above, for verification."))```
now that i look at it myself
i can see whats the problem
but how do i customize this
What were you thinking of customizing?
well
apparently
in this class only one type of error message is defined
and thats the one where password doesnt match with conf_password
my problem is
there is more errors that happen UI wise when it comes to registering
for example if i were to try entering password thats shorter than defined min_lenght for passwords
i want the error to be displayed as "Please enter a password that consists of 6 or more characters."
and not "'password_mismatch': _("The two password fields didn't match.")"
{% block content %}
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Forum - SignUp</title>
<link rel="stylesheet" href="{% static 'signup/style.css' %}">
</head>
<body>
<div class="signin-box">
<h1> Sign Up</h1>
<form method="post" action="">
{% csrf_token %}
<div class="textbox">
<input type="text" name="username" placeholder="Username" maxlength="10" autocapitalize="none"
autocomplete="username" autofocus="" required="" id="id_username">
</div>
<div class="textbox">
<input type="password" name="password1" placeholder="Password" autocomplete="new-password" required=""
id="id_password1">
</div>
<div class="textbox">
<input type="password" name="password2" placeholder="Confirm Password" autocomplete="new-password"
required="" id="id_password2">
</div>
{% if messages %}
{% for message in messages %}
<div class="help">
<p><span style="font-size: 20px">⚠</span> {{message}}</p>
</div>
{% endfor %}
{% endif %}
<input class="btn" type="submit" style="opacity: 1 !important;" value="Sign Up">
</form>
</div>
</body>
{% endblock %}```
If it's just password length you're concerned about, I'd say use the minlength/maxlength attributes. Saves you some time having to develop this piece..
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/password#minlength
well not just pass leng
i also want to alert user when he tries to signup with a username that's already taken
but this actually saves me thanks
altho im rn really interested into finding out if it's possible to create an actual error messages that recognizes and alerts the user when he makes the error
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class CustomUser(AbstractUser):
def __str__(self):
return self.username
class Blog(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
author = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
class Comment(models.Model):
author = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
class Meta:
ordering = ['date']```
here in my models.py
I have a CustomUser Blog and Comment
every Blog should be able to have multiple comments
When I go to the api in the blogs list in the author field it gives me the ID of the author. But I want the username and not the ID.
How do I fix this?
Same for the author fields in comments.
this is not directly related but
โrepeat passwordโ dialogs are bad UX IMO
you should prefer revealable password inputs
you know, the kind which let you unhide what you typed
anyone can help me with this?
How do I make it for my webpage to have different pages if you scroll down
like when you click the links it drags you down
Put an id on an element and setup an an href equal to that element id. For example:
<a href="#aboutUs">Click me</a>
<div id="">...</div>
Will it automatically go down even though I have a background image in my "body{ }" css?
I want a different background for that
Alas. I figured out my Flask 2.0.1 issue around threading and refactored my little single thread app to now support multi threading. ๐ฅณ
this line is of a django docs what it mean i cant get where i showed run .schema The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file and the database migrations shipped with the app (weโll cover those later). Youโll see a message for each migration it applies. If youโre interested, run the command-line client for your database and type \dt (PostgreSQL), SHOW TABLES; (MariaDB, MySQL), .schema (SQLite), or SELECT TABLE_NAME FROM USER_TABLES; (Oracle) to display the tables Django created.
Hey guys, how can i build a SaaS app ?
is there any way to get duration between two string dates ?
your question isn't for #web-development
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
In python 3 app i am setting up a hello command and now it is setup successful but if i want to setup one more command in same file so how to. And i am writing down the second command then it is not working please help
i wanted to add it, but first i wanna take care of my current problem, i want the appropriate error message to be displayed when user tries registering incorrectly
Show the code
hi
i am having trouble saving data to user account in django please can someone help
Many people in #846514617261621292 have created web apps that will coordinate with other people as to where the pixels will go... where do I start learning how to do something like this?
well this is where the fun begins @rustic wave
i havent used the Pixels thing
it sounds cool
is cool*
so the way this works (as far as i know)
you send a request to an api that pydis has
ya no i get how it works
but i dont get where do i get started learning to be able to do something like this
first you need to pick a framework
i would use django
but flask would probably be better for this
next
send some requests
ive messed around me django and flask a tiny tiny bit...
django brianpoped me
flask made a bit more sense
django kinda does that
it is more effective for large and scaled projects
so next
make some requests
you can use the requests module
!pypi requests
@rustic wave
ok cool
so now we send requests to the api
idk what it is
probably has some docs to it
so any good resources to learn something like flask?
flask documentation
tutorials on youtube
ya no ik how to interact with the pixels api.. my question was how to make something like pixels
ok ty!
@rustic wave i found this playlist to be quite helpful while i was learning
How To Build Websites with Python and Flask! In this videos I'll walk you through building a very basic website with Flask. You'll see just how easy it is to get started with this powerful web framework!
Python is great, and building websites with Python is even better! Flask makes it super easy to build websites with Python quickly and eas...
it covers practically everything
ty!
wait haang on
you want to make something like pixels?
ye
and not just interface with it, but build it yourself?
o wow this just got a lot harder
lmao
so if ur building this
you really have no choice but to use django
it has the best database support
ah ok
uh so you would probably need to learn it
and what about something like this
https://subsystems.bast-development.com/
basically it will coordinate between multiple ppl
and tell them where each pixel will go
so liek basically a hivemind i guess
uh i guess
but that rlly isn't neccesary
@rustic wave
we should let the people collab
and do whatever they want
we also would want mods on our db
to check for any criminal ... uh ... imagery
hello
database = SQLAlchemy()
DB_NAME = "database.db"
def create_app():
app = Flask(__name__)
app.config["SECRET_KEY"] = "YAEgysUiDlc1yNbe4MF10tMXaYqGbbo0"
app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{DB_NAME}"
database.init_app(app)
def create_database(app):
if not path.exists("website/" + DB_NAME):
database.create_all(app=app)
print("Created Database!")
```Hello, so i have this and it stores my `database.db` in `/website` however i would like it so be stored in `/website/database`. can somebody please help.
`EDIT: solved the problem now!`
Can u add a token varible in html <a> tag? Like the token I have is jwt token?
Hey so
https://www.worldometers.info/coronavirus/#countries this is the website
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
import requests
from bs4 import BeautifulSoup
h = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
r = requests.get("https://www.worldometers.info/coronavirus/#countries")
c = r.text
soup = BeautifulSoup(c,"html.parser")
main_table = soup.find("table", {"id":"main_table_countries_today"})
print(main_table.find_all('tr',{"class":"odd"}))
and this is the code
why would it return an empty list ?
cuz we see there are rows tagged with tr and class 'odd'
Hey why u block me
I'd suggest you always test your patterns in the chrome console first or use the python interpreter to test them
okay 
_ _
I want to use this module to create certificates for my domain, but there's a few things I don't understand. Why does it end up with a .crt file? Thought certificates have the .pem extension?
also if anyone has a suggestion for a better way of creating certificates, then I'm open for that
ey is flask worthwhile?
As always, it depends what you want to build
If you open that site on a browser, notice that there's a delay before the table gets populated? I assume that there's some JS that populates the table after it initially loads. You might want to inspect the HTML you get with requests and scrape using that instead of looking at what's on the browser.
From the initial load, it seems that there are already tables with data, but there are no classes associated with each tr elements.
i mean for job searching
Would someone be willing to help me help chocolate. It is a question about imports and python files.
how do i get a pong message from aiohttp?
hi can someone help me in django project
be more precise in your questions
Why u block me
TypeError at /search-posts/
as_view() takes 1 positional argument but 2 were given
class BlogSearchView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' def get_queryset(self): query = self.request.GET.get('q') return Post.objects.filter(title__icontains = query).order_by('-created_at')
this is my views.py
path('search-posts/', views.BlogSearchView.as_view, name = "search-posts"),
the above is url
<form action="search-posts" method = 'get'> {% csrf_token %} <input type="text" name = 'q' placeholder="Search Post"> <button type="submit">Search</button> </form>
the above is form used to make it
Why am I getting that error how to solve it?
@native tide .as_view is a method, so it should be called
can anyone help me with django?
Ask the question
this my model for a loan
I want to change the date_given to datetime.now when the status is set to 'approved'
how to do this
you might be able to use signals
ive never used them but i looked into them a while back when i was first learning about models, from what i recall they can probably do what youre asking
thanks a lot!, exactly what I was looking for, you really saved me a lot of time!
hey! I wanted to know how much time should it take to make an API using django rest framework
Hey i wanted to know why the _set command in django dosn't worl
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'User' object has no attribute 'Post_1'
>>>```
Hi, got a simple flask demo.
I render template with data=data
When i use {{ data }} in html it works
however in js, var data = {{ data }} doesn't work. How would i do it ?
i'm thinking you must've separated the js file
the templating probably works only on the html file
even if i try it in the console it should be defined correct ?
wait, what should be defined?
if i used console.log({{data}}) for example
nope
the {{ }} formatting is processed at the server
before being passed unto the client
meaning the {{ }} tags are removed before it reaches the browser
hey, does anyone know a better module than requests for webscraping
you can open urls with BeautifulSoup??
im sorry idk im new to this
Any one please
you use them when you want a custom domain to point to your server
isn't that just an A record?
looks like dns to me
yeah, I meant like "custom domain to point to your server" isn't that just an A record?
not sure what the technical definition is
messages.error(request, form.error_messages["msg"])
print(msg)```
any reasons why these lines of code in views.py upset my compiler so much? it displays "KeyError 'msg'" as an issue
```class UserCreationForm(forms.ModelForm):
error_messages = {
'password_mismatch': _('The two password fields didnโt match.'),
'password_short': _('Password is too short.')
}```
this is the dictionary im trying to access and get values from
its basically a record telling that go to this ip if you hit a particular domain name also the ns2.digit.........com is digital oceans library of sorts full of records that map/point you to an ip address or to a server
nvm i've figured whats wrong
Hi, Whats the best way to do this.
I have my mainpage route and another route called data.
the data route redirects back to the mainpage but carries a param called data.
Im currently just using sessions but is there an easier way like redirect("/", data=data)?
ุฒูู
Question.
Django related. If I want to update a propert of a object but the property is dynamically ?
How can I do that ?
*property
For prop in list:
Object.prop = value
setattr
huh then what do you expect
I have used the update method on the object.
what kind of object is it
Can you maybe explain your question
what is its type
Charfield
Text
@native tide Hey, I saw your inquiry in the Flask Discord about securing an API. I too am working on an API in Flask, and I will likely run into the same issues you are. I'd love to see what you discover.
Additionally, I was going to recommend JWT, but I don't have much direct experience working with that in Flask.
You are currently using your own name server. Ns records allow delegating this task to another provider, if I get it right
padding?
yeah padding in css
padding wouldn't be a space between the elements, technically
you can look into flexbox
what exactly do you want to do?
oh ok
you can think of it this way: padding is between everything in the element and the border, and margin is between the element's border and the next element's border
oh ok thanks for the info
i am running into an error while trying to launch a django / socket.io project to heroku. Anyone have experience?
is pyppeteer faster than selenium?
out of curiosity googled.
yes puppeteer is faster than selenium up to 30%.
and it is even fastest for demo web sites
sry , i googled it and found pupeteer is faster but i wasnt sure about pyppeteer
ยฏ_(ใ)_/ยฏ no benchmarks for pyppeteer
hi'
can you show index.html
I would recommend separating your html from css and js
css, js and images come under static files
i did it from a html builder
you need to handle static files in a diff way.
the link I sent above has all the details for it โ๏ธ
I would recommend you to also look into template inheritance
is there a way to know if a client have disconnected from Flask? like for example a user is no longer connected to the@App.route('/')
now works, ty โค๏ธ
nice ๐
I have a website that I deployed in Heroku. It does scraping on the button click. But it takes a lot of time and in Heroku timeout occurs after 30 seconds. Now how can I make the script run in the background?
PS: I have used Selenium for scraping and web app is made in Django
Edit : After the script run it gives a download option to the user.
Hello. I'm having issues with django. My server isn't serving static files. It's on digital ocean and I'm using nginx and guniicorn. I'm not a Linux guy So I don't really know much about it. What files Do i need to share with you for you to help fix it? Please help. Thanks
I know Django channels and Django a bit... You could drop it and see if it's a common one?
Hi quick question, whats best practice for api calls? single bulky calls or small targeted calls?
should i request for the whole inventory and send product info via props or call a single product on each product page?
Hi, is it possible to pass arguments through a redirect?
So like:
data=1
return redirect("/", data=data)
flask btw
request only minimum necessary amount for current render
pagination is supported at API frameworks level usually
keeping somewhere hidden data, which you do not render, is usually a bad practice
hi this is my main code : ```py
import requests
import uvicorn
import json
from fastapi import FastAPI
discord_token = "BotToken"
app = FastAPI()
@app.post('/discord-user')
async def discord_user(id):
user_id = id
headers = {'Authorization': f"Bot " + discord_token}
r = requests.get(f"https://discord.com/api/users/{user_id}", headers=headers)
data = r.json()
hash = data["avatar"]
data["avatar"] = f"https://cdn.discordapp.com/avatars/{user_id}/{hash}.png"
data["avatar_gif"] = f"https://cdn.discordapp.com/avatars/{user_id}/{hash}.gif"
return data
this is the test file:
```py
import requests
r = requests.post("http://127.0.0.1:8000/discord-user", headers={"id":"690099836963651695"})
print(r.json())
i get ```
{'detail': [{'loc': ['query', 'id'], 'msg': 'field required', 'type': 'value_error.missing'}]}
y ?
I think you need to pass them into the data kwarg and not the headers kwarg
Try that out, @autumn veldt
i.e. requests.post('url', data={'id': whatever})
ok
I made a schedule keeper of sorts.
and I only have 1 more obstacle
When the time for the schedule arrives, I want it to send a notification...
but I have ZERO idea of how to do this background checking :(
Using Flask
ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Can we have wagtail cms based on user ???
What errors are you getting
Can I make static websites using python flask?
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def hello():
message = "Hello, World"
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
I'm building a django app where I want to run cron jobs based off data that currently exists in the database. Once the cron jobs are complete I want to send a put request back to my django server and update with the new date (or modify the db object with the ORM using a task script whatever is easier). I am looking at celery for this and seems like it is what I'm looking for but not totally sure. Anyone know if there's a better option? I haven't really worked with cron jobs/task runners and stuff before
celery is better than cron
you will have total control at your code level about your tasks
why is celery better than cron?
i don't really know anything about cron, which is why i ask
https://www.reddit.com/r/Python/comments/m2dg8/explain_like_im_five_why_or_why_not_would_celery/
read here different reasons
as for purely my reasons... cron lives outside of application. python at best can be only accessing its internal control.
while celery lives basically purely inside your code project and only uses Redis database as memory storage to work.
I prefer having things like that tightly packed into my code project
61 votes and 26 comments so far on Reddit
yeah I guess if you deploy, having it all centralized in a .py file is easiest
surely celery uses cronjobs itself
@inland oak cool thanks for confirming that for me. As long as I can perform actions on the DB and schedule tasks based on DateTime fields that's all I really need. Sounds like i should be able to do that fairly easily with it
easiest way to do this on linux is by running export DJANGO_SETTINGS_MODULE=<projectname>.settings
are you running trying to deploy via ASGI or WSGI?
someone know where i can learn more about alignment? i want try something, for example put this graph on the center of the page, try to put the graph on the left and one table with some infos on the right side of the graph...
one of the most popular ways to do this is with flexbox and columns, although libraries like bulma can achieve the similar thing without writing any css
can anyone help me with google programmable search engine?
i am not able to do an image search
Hi, I am creating a simple flask web blog application with bootstrap, When i click certain things of navbar, that shows not found and changes it's end points automatically, can anyone help with this please.
Hi, I am creating a simple flask web blog application with bootstrap, When i click certain things of navbar, that shows not found and changes it's end points automatically, can anyone help with this please. Plox help
what do you mean
Trying to deploy via wsgi
What is the best way to query an existing URL API via Flask application?
Whats wrong with margin-top?
Then put a container up there and leave it empty. And when they do the thing, select the element and put the thing in there.
So what you have is
<div class="global-container">
<div class="container-for-new-thing"></div>
<div class="container-for-buttons">
<!-- the code you have above -->
</div>
</div>
And when you create the element of the thing that you add with JS, you select that container for where to put it
Which is just an empty space already there.
you would probably use more appropriate classes
But that is why you see every element always is contained in a millions divs
How do ya think
do you guys think threejs is too bloated?
wanna use it with my nextjs app but feel like it might bloat my site even more
When I return a JSON object, how can I have the Response code after it
is there a django method for validating whether a string meets the requirements for a username
im working on a flask application and i faced a wierd problem when i uploaded to production all my apis now got /static/ before the actual api and that cause a problem that when i reload the web fall because there is no /static/ api why this happens and any idea how can i fix this?
username_validator = RegexValidator(r'^[\w.@+-]+$',_('Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.'), 'invalid')
File "<console>", line 1, in <module>
TypeError: 'str' object is not callable```
why error
where is the password validation code for django
Hello, I'm new to django and I have 2 problems I need help with.
Firstly,
I have a view that showx "You are logged in as [x]". After login is successful it shows "You are logged in as anonymous user". How do I fix that.
Secondly,
I have a remarks form on lower-level users. This allow highLevel users comment on lowLevel users. The form is supposed to take both the id of the logged in user and the Id of the user to be commented on and create a database entry associated with both users. How do I make the form collect both users Id (I used foreignkey to link the models)
THis is so long
i am getting an error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. when trying to deploy to heroku. Any idea?
i would start out checking that your requirements.txt matches your settings.py INSTALLED_APPS object
i always found that part of deploying to heroku to be a pain point
but im noob
obviously you wouldnt need to worry about local app directorys being included in that
i'd also look at your traceback to see at what package it is failing with
Should I be putting everything in the requirements into the installed apps?
not necessarily
copy paste both to me please
try committing to heroku again and see what the traceback says as well, it will show the specifc package it is having trouble with i think
no
check the logs
Hi. Have a quick question about the use of webapps for certain stuff
Trying to create a website "hybird"(?) with django. Right now I'm on the part of creating a homepage... do I use the main app, or create another?
Watching a tutorial, and the person used the main app
already created another and I'm somewhat worried it wasn't necessary, because then I'll have to delete it somehow
by "app" do you mean "Django app"?
I'm (still) very confused
but
err, app, yeah
two apps in my project... the main one, and then one I created that may not be necessary anymore
a project
contains one or more apps
you can think of apps as plugins
that can be added/removed at will
to change the functionality of the project
yeah
in general
each app has its own sphere of responsibility
for example, say you're designing Instagram
you might have an insta_images app to handle image processing, insta_chat for chat, insta_store for the store, etc.
oh, yeah
okay, well....
either this person in a tutorial I'm seeing set it up somehow in the video or not... but he created a views.py and other things in what looks like his main app to create a homepage
do I do this... or should I keep the other app I created and put all the stuff there...?
that depends
on your planned architecture...?
I can't answer that question for you
but
it's probably not somtehing yu need to worry about rihgt now
honestly, I'm not sure now lol
just
stick to one app
if you're starting out
this is not something you need to care about
my big worry is deleting the extra one and breaking stuff
then don't delete it
just leave it there
mmm ok
Hey how do you change the change password form in Django
https://docs.djangoproject.com/en/3.2/intro/tutorial07/#customize-the-admin-look-and-feel
Customize the admin look and feelยถ
Hi, I'm working with leaflet, Flask & sqlite3. I'd like to generate a layer on the map that covers the entire map apart from small circles where the user has been. How would be the best way to go about this? Would I need to have JS render images with circle cutouts or would it accept a huge multipoint geojson also?
The coordinates it would need to generate circles around are stored in the database
i want to connect my html form so that it uses the rest api and uploads a file using some function in flask ..... how do i connect the html form and rest api??
any idea why the background and avatar images are not working on the server? how can i fix it ?
@wispy dirge
wait let me send it again
if request.POST['password1'] == request.POST['password2']:
user = User.objects.create_user(username = request.POST['username'],password = request.POST['password1'])
user.save()
**I have done with this method when I was learning python last week and It worked perfectly fine now I tried again its not working even both are same **
can you just print request.POST
we could check if those fields are included
or if the forms were messed up
guys i have a form like the img
how i can make when someone click on the Search button he get the name input of the first area to go to a link like: link/input_name?
example: www.google.com/ab
is the site static or using any framework?
its static i think . _.
have you worked with js before?
you will need some js to make that happen ๐
the process would be to listen to the click event on the button and then read the content of the form input field
then redirecting the user
actually he use something like:
<form action="https://www.itemsearch.com" method="POST" class="u-clearfix u-form-custom-backend u-form-spacing-15 u-form-vertical u-inner-form" style="padding: 10px;" source="custom" name="itemsearch" redirect="true">
...
<div class="u-align-center u-form-group u-form-submit">
<a href="#" class="u-border-0 u-btn u-btn-round u-btn-submit u-button-style u-custom-font u-font-lobster u-gradient u-none u-radius-50 u-text-black u-btn-1">Search<br>
</a>
<input type="submit" value="submit" class="u-form-control-hidden" required="required">
</div>
i was thinking if i could just change the form action to have something like in python: form action="link/"+var_input
not sure how that would be done tho
hi guys, have any of you used dash plotly with flask? I'm trying to secure it with flask security too but i don't know how to do it. thank for your time
this link will be a good reference
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xv-a-better-application-structure
I have a website that I deployed in Heroku. It does scraping on the button click. But it takes a lot of time and in Heroku timeout occurs after 30 seconds. Now how can I make the script run in the background?
PS: I have used Selenium for scraping and web app is made in Django
Thank you for your reply. Well I am specifically moving my Flask @spare ridge.routes to another file. I tried moving them, and then importing the initialized app = Flask() to another file, but it didn't work.
do see the link i provided what you need is blueprint hierarchy file structure
Another peculiarity is that the routes module is imported at the bottom and not at the top of the script as it is always done. The bottom import is a workaround to circular imports, a common problem with Flask applications. You are going to see that the routes module needs to import the app variable defined in this script, so putting one of the reciprocal imports at the bottom avoids the error that results from the mutual references between these two files.
This is what I needed!
what?? um no its not done like that ..... i really suggest you go to that link or search for blueprint to scale flask app
dude that is one of the top 2 tutorials on flask ........it does work cause i have completed that tutorial
still i'll give you the github of that version and
https://github.com/miguelgrinberg/microblog/tree/v0.15
the official doc
https://flask.palletsprojects.com/en/2.0.x/blueprints/
Hi! I have some difficulties in implementation of validate() method for ModelSerializer.
So, there are some rules that check if data that is gonna be saved to db is valid.
The problem is that in case of update this should be checking against merged instance and validated_data
and for create I should perform checks for validated_data only
Using 2 different serializers feels not DRY to me.
Checking for self.instance and validated_data.get("field_name") is also kinda ugly, especially when it is partial_update
Is there some elegant approach to it?
python manage.py migrate @low glen
stop server
run migrate command
start server
this is coming
but now i had run migrate , will it be a problem now
it will be even better ๐
Hello I was doing programming with Mosh's Python course (https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=19732s) but There is a problem when making migrations in Django it is always telling No changes detected . But I tried everything They told but it is still not working . Anyone help me
Python tutorial - Python for beginners - Go from Zero to Hero with Python (includes machine learning & web development project).
๐ฅ Want to master Python? Get my Python mastery course: http://bit.ly/35BLHHP
๐ Subscribe for more Python tutorials like this: https://goo.gl/6PYaGF
๐ Watch the new edition: https://youtu.be/kqtD5dpn9C8
๐ Get my FREE ...
ModuleNotFoundError: No module named 'flask._compat' i have already flask installed in my system but i get this error
some one help me pls
these are for when you add or change the models
once you have made a model for your web app, then you register your app in INSTALLED_APPS and then you can run makemigrations and migrate
hey guys one question
so I was planning to build a full stack app with MERN, but I want to integrate a recommender system(coded in py) with it. How do I send the data to my node.js backend actually?
is this the right approach or will it be better to move to a django/flask based stack?
You can send it from Python to Node using your own API if you wish
I Did it but also this is coming
but that would mean using two servers, right?
DM me
You can use bpaste or type ` 3 times followed by py
!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.
you can ask here or DM me
I'm planning to make an image api
I will be using heroku as my host (I don't know where else I could host the api for free ofc since it's only a project)
But since heroku reverts back to its original form when the server restarts the images will be deleted so I need an online database Do you guys know any?
Are you storing image links or files?
Files
Ah, then no idea
If they were image links what would you have recommended
Firebase, Mongo, Supabase, anything
Supabase is still in early version but do you have something that is SQL?
@arctic shard you may still use firebase. You just have to convert image to base64 (so it outputs as a string) and put it in firebase
when you fetch base64 from firebase and want to render it as an image on html -> https://stackoverflow.com/questions/8499633/how-to-display-base64-images-in-html
links look dated, you may just do something on the same lines. Firebase API must have changed in 5 years
But I kinda wanted to have tags for each image so using firebase will make it bad
You may also use custom metadata attached to a file on firebase: https://firebase.google.com/docs/storage/web/file-metadata#custom_metadata
I ain't selling you Firebase ๐ just that if you have really trivial use cases then you could just use it simply
I found this
https://www.freesqldatabase.com/register/
Completely free database hosting
Instant account activation
5MB of database space
24 hour support
Err for images -> Probably not
also base64 encoding images generally leads to alot of bloat
an image api on a free Heroku instance is probably not the best idea
Just a project for testih and understanding APIs
also I shouldn't store images as base64 because it might will bad?
I thought it will be smaller since string
So using firebase as database is better than using sql database for images?
Err they're probably all equally bad
I mean you might only be storing a few images and serving a few images
in which case you might? get away with it
but any sort of load on any of these cloud databases or free tiers will probably blow through your allowance in no time
I don't have allowance 
the allowance the free tier gives you
e.g. the amount of usage your allowed before it cuts you off
Firebase gives 1gb storage https://cdn.discordapp.com/emojis/788882232441307154.gif?size=64
thats just storage
that doesnt include the bandwidth cap
If you want my advise: just store the images on heroku
What do people with proper hosting do with their images?
generally store them as static files or use a CDN setup
idk how discord has their setup but generally its something like a cloudstorage setup and served globally, or its stored in a managed database
But either way you blow through bandwidth rather quick with image serving
If they are generally stored...
The system copies the file and give it to the user?
I recently wrong a setup for this sorta thing https://github.com/ChillFish8/lust
I can't find any api reference for this stuff
their is a surprisingly low amount of info around this stuff.
mostly because no real good solutions exist ig
but the setup i linked to above is definitely not suited to low ram, low storage servers
is this cdn like?
https://docs.thecatapi.com/
TheCatApi // Developer Experience
Get your API Key from - https://TheCatAPI.com
Here you'll find the API reference & Code examples for:
1. Searc...
Ig you can call it that?
In most cases it's probably just a bunch of static files being served by nginx
Tbh I'm trying to make a ||thigh|| api ๐ณ And I kinda wanted it to be open source so static Posting the images in github might get me in trouble
Mm for end use I dont think it would be a good idea to try run it on a free server
this is the error
image= models.ImageField(upload_to='uploads/', blank=True, null=True)
thumbnail= models.ImageField(upload_to='uploads/', blank=True, null=True)
date_added= models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-date_added',)
def __str__(self):
return self.name
def get_absolute_url(self):
return f'/{self.category.slug}/{self.slug}/'
def get_image(self):
if self.image:
return 'http://127.0.0.1:8000' + self.image.url
return ''
def get_thumbnail(self):
if self.thumbnail:
return 'http://127.0.0.1:8000' + self.thumbnail.url
else:
if self.image:
self.thumbnail = self.make_thumbnail(self.image)
self.save()
return 'http://127.0.0.1:8000' + self.thumbnail.url
else:
return ''
def make_thumbnail(self, image, size=(300, 200)):
img = Image.open(image)
img.convert('RGB')
img.thumbnail(size)
thumb_io = BytesIO()
img.save(thumb_io, 'JPEG', quality=85)
thumbnail = File(thumb_io, name=image.name)
(this is the code)
I am making a flask website with use of bootstrap. When I click on options provided on nav bar, sometimes some options changes their end point to the file from which they are being rendered and give not found error๐pls help
@quick cargo can ya help please ๐
Ping when anyone is telling a solution going to sleep bye
Hello!
I have deployed a Flask application on a server but all routes return a 404. The central log of the server is unreachable for me due to the provider.. so I'm looking for ways to test or call routes from python side to try to see potential error messages.
This 404 on all routes is a big black box for me and I can't find the culprit line.
PS: App runs on my local, but the server deployment is using apache and wsgi.. hence the difference.
How can I find the error?
Its funny to discover an exploit to my own website
the experience must've been funny and relieving at the same time
Hi I need help in django.
I've just started learning it and until now i've been using manage.py runserver <ip address:port> to run my django project. I've heard that it shouldn't be used for deployment, that it's just for testing if it works.
Any advice on deploying my django project to a server??
Gunicorn as standard... but there are alternatives.
https://docs.djangoproject.com/en/3.2/howto/deployment/
You will need handling static files differently
In addition to gunicorn
Best practice to handle static files with nginx
ok noted
In advance you need to apply manage.py command
Which gathers all your static files
In one folder
it's in the manage.py help right?
Should be mentioned here
ok thanks
oh ok, it's the STATIC_ROOT right?
Not remembering
U a welcome
hey guys i have a school project that consist to do an app of scanning network equipment's like switches and routers i did the python scripts in a traditional way but now i need to integrate my work in a web app but every thing is stuck i never used django before i even tried the simplest things to add a bootstrap page no success i dont know how use the scripts in this web app i feel so lost and time is ticking please any help
if you need something simple and quick, you should use flask instead of django
the directory structure is much simpler compared to django's
@teal bane
i haven't actually used flask that much
i once started a project with it but quit halfway
but flask is simpler and a easier to learn than django
you dont know neither django or flask ?
i know them
and have used them both
but i don't have much experience and expertise
my work is not so hard i i stated i need authetication then a form then send the infromation to script script do its job return response if you can please help me
sorry i've kinda forgotten how to work with flask
Help
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.
I'm working on a program that makes requests to several different APIs(GET, POST, PUT). Mostly Get and and PUT. Right now the project takes roughly 40 minutes to finish mainly because for PUT, I can only update 1 item at a time.
How can I make it fast? I looked into multithreading and came across gerequests. Is gerequests something I should look into?
https://stackoverflow.com/questions/38280094/python-requests-with-multithreading
I believe you want async
Actually I'll give these a shot.
what would be faster asyncio or gevents?
I have a flask endpoint running right now and my bottle neck is this one tasks that does a look of async requests.gets but I feel like my implementation is off
I'm running gunicorn with gevent config and regular flask. The flask app is monkey patched with gevent so in theory my async stuff should execute pretty fast
loop = get_or_create_eventloop()
future = asyncio.ensure_future(multiCallPrice(tokentemp))
prices = loop.run_until_complete(future)
Idk why but I have this in there itโs the only way I can get it to run
def get_or_create_eventloop():
try:
return asyncio.get_event_loop()
except RuntimeError as ex:
if "There is no current event loop in thread" in str(ex):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return asyncio.get_event_loop()
async def multiCallPrice(loopOver):
tasks = []
timeout = ClientTimeout(total=40)
async with ClientSession(timeout=timeout) as session:
for token in loopOver:
task = asyncio.ensure_future(async_get_request(session, url, token['token'], token['decimal'], shareAmount))
tasks.append(task)
responses = await asyncio.gather(*tasks)
return(responses)```
hey how do you make it such that your flask server is updated every x times
i am using a mysql database and when any database changes are made it doesnt reflect in the webpage
I think you are looking for a more dynamic frontend with javascript
something like... simple js script which checks from time to time update from your backend, and updates the page
basically client-side code
your backend should expose its data in form of JSON API for this
no idea what that is but i think i should explain it again
i added a record to the database and restarted the flask app the change was there
but when i removed that record and refresh the page the record stays
so i think i need something that restarts as such my flask app every x times
so the changes are visible every time
the sql is updated
it is completely not the right approach
you are right now rendering page as fixed HTML document
you need to change output of your information to JSON format and having available at some end point
while rendering your view page with addition of JS code which fetches data from your JSON API endpoint
then you can add to js code some addition, which will check for updates and rerender it automatically
okay what do i need to do
ok
How do you guys do queue management with fastapi?
I have built a ML API deployed on GCP Cloud Run with a docker image but on some cases the response takes time and I would rather it goes into a queue like redis or something. I did achieve that by making a docker compose but then I couldn't deploy docker-compose with CI CD on GCP. I don't want to get into kubernetes as it'll be too complex for a small scale solution like mine.
I am making a flask website with use of bootstrap. When I click on options provided on nav bar, sometimes some options changes their end point to the file from which they are being rendered and give not found errorbasketballpls help
Flask or Django Lets fight ๐
image= models.ImageField(upload_to='uploads/', blank=True, null=True)
thumbnail= models.ImageField(upload_to='uploads/', blank=True, null=True)
date_added= models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-date_added',)
def __str__(self):
return self.name
def get_absolute_url(self):
return f'/{self.category.slug}/{self.slug}/'
def get_image(self):
if self.image:
return 'http://127.0.0.1:8000' + self.image.url
return ''
def get_thumbnail(self):
if self.thumbnail:
return 'http://127.0.0.1:8000' + self.thumbnail.url
else:
if self.image:
self.thumbnail = self.make_thumbnail(self.image)
self.save()
return 'http://127.0.0.1:8000' + self.thumbnail.url
else:
return ''
def make_thumbnail(self, image, size=(300, 200)):
img = Image.open(image)
img.convert('RGB')
img.thumbnail(size)
thumb_io = BytesIO()
img.save(thumb_io, 'JPEG', quality=85)
thumbnail = File(thumb_io, name=image.name)
print('Hello world!')
@digital hinge @opaque rivet thanks both
Hello
So i have this form that lets the user make a poll and add choices to it
It consists of 2 ModelForms on for the quiestion model and the other for the choice model
forms.py
from django import forms
from .models import Question
from .models import Choice
class NewPollForm(forms.ModelForm):
class Meta:
model = Question
labels = {
"questionText":"Poll question"
}
fields = ("questionText",)
class NewChoicesForm(forms.ModelForm):
class Meta:
model = Choice
labels = {
"choiceText":"Choice"
}
fields = ("choiceText",)
models.py
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Question(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
questionText = models.CharField(max_length=150)
datePublished = models.DateTimeField(auto_now_add=True)
def str(self):
return self.questionText
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choiceText = models.CharField(max_length=200)
choiceVotes = models.IntegerField(default=0)
def str(self):
return self.choiceText
I want to let the user be able to add as many choices as they want
Like there be a (+) button or (add another choice) in the form in the image above
Oh i forget
Here's my view that handles this page
views.py
def newpoll(request):
if request.user.is_authenticated == True :
pass
else:
return redirect("users:signup")
if request.method == "POST":
qform = NewPollForm(request.POST)
cform = NewChoicesForm(request.POST)
if qform.is_valid():
newpoll = qform.save(commit=False)
newpoll.user = request.user
newpoll.datePublished = timezone.now()
newpoll.save()
cform.instance.question = newpoll
cform.save()
return redirect("polls:details", pollid=newpoll.pk)
else:
return render (request, "polls/newpoll.html", {"qform":qform, "cform":cform})
else:
qform = NewPollForm()
cform = NewChoicesForm()
return render (request, "polls/newpoll.html", {"qform":qform, "cform":cform})
Thanks in advance
I know this isn't the right place to ask about react but anyways ........
When I do import { Navbar, Nav, NavDropdown, Form, Button, FormControl } from 'react-bootstrap';
I get the error Module not found: Can't resolve 'react-bootstrap in file_location_here
I tried doing npm install react-bootstrap bootstrap@4.6.0
but the results are unchanged
What's the problem?
How to get started on a basic website, ik there is flask but any docs or starters.
ah tysm
a little bit outdated by few years, but still good one
in most of them everything is still correct, but in some places syntax got changed
in my opinion it is even good because allows you to think more what needs to be done instead of copy pasting
i never copy andd paste so its ok!
ill just read it
and refer to it
New Release 
I am deeply in love with Python 3 and it's ecosystem! 
Hello guys, a couple weeks ago i published my first book on Django 3 and want to share it with you: https://www.amazon.com/Django-3-Beginners-Andrey-Bulezyuk-ebook/dp/B095V5P2QM/ref=tmm_kin_swatch_0?_encoding=UTF8&qid=&sr=
I'd be glad to receive honest feedback!
Django 3: For Beginners - Kindle edition by Bulezyuk, Andrey. Download it once and read it on your Kindle device, PC, phones or tablets. Use features like bookmarks, note taking and highlighting while reading Django 3: For Beginners.
seems sus
Why?
I created token authentication system in Django rest framework, after getting the token, how should I authenticate myself?? any suggestions
is a UI necessary?
@steel reef UI is not needed. You need to pass the JWT Token (generated in backend) with every other request unter "auth" "bearer <JWT>"
take a look here: https://www.amazon.com/Django-3-Beginners-Andrey-Bulezyuk-ebook/dp/B095V5P2QM/ref=tmm_kin_swatch_0?_encoding=UTF8&qid=&sr=
Django 3: For Beginners - Kindle edition by Bulezyuk, Andrey. Download it once and read it on your Kindle device, PC, phones or tablets. Use features like bookmarks, note taking and highlighting while reading Django 3: For Beginners.
got it
So uhm...
cough
This is NOT...
What I wanted
Is there a way to have html render correctly from a string?
Using Flask
I am choosing to learn some front end framework to complement my django rest framework
what would you recommend as the most easiest and nicest choice, preferably closer to django approach in development?
Angular? Vue? React?
Nvm, using Markup worked



