#web-development
2 messages · Page 224 of 1
u a welcome
Why is my flask application sending insane amounts of post methods? Everytime i make a post the next time it doubles? (When i refresh the page and make post requests it resets)
'session': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0x0000026E97ABC8B0>>
how to get the REAL session id?
Hi guys, we currently develop a free hosting control panel and we want to support Python as well.
What is the standard procedure to install additional python versions on a server (debian, ubuntu). Do you use pyenv?
Each site user (ssh user) should be able to install it's own needed python version
how to change timezones in django
I have a field in my data base which gives the current time but the time is not from my timezone
I am using allauth and receiving the error: SocialToken matching query does not exist.. Has anyone experienced this? I have triple checked the site ID and its correct
I can login fine with google. But when I use this code below, I retrieve the error above:
token = SocialToken.objects.get(account__user=request.user, account__provider='google')
Hey, is there a way to pass a variable or something to a base template? (django)
Hey @manic crane!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
jinja allows conditionals and embedded python in the html. read more here: https://docs.djangoproject.com/en/4.0/ref/templates/language/
discord said the message is to long
Hey @manic crane!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
thanks
is there a way to reset all the values of a collumn everytime a server starts?
#help-cherries .....?
using Django & Jinja to make an html page, is it possible to share a python variable directy to a JS script inside that html page ?
return render(request,'report.html',{'users':users})
report.html:
<script src="{% static 'data.js' %}"></script> <-- how to access `{{users}}` from inside `data.js`?
@grand orbit tysm for posting it here😇
Related to this: since Electron ships with chrome, I've thought about doing the same, but not with chrome.
Is there a lightweight browser that can be freely shipped with an app?
Flask:
For an Input box text ,
can i check in real time if a string is entered correctly and show a flashing message in html ?
Or should this check based on regex, to be done on the input box?
<input type="text" id="uname" name="uname" pattern="[a-zA-Z0-9]+" minlength="4" maxlength="10">
Django has json_script filter (https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#json-script)
and for smaller amount of data, there's also escapejs that can be embedded directly inside a <script> tag
For jinja, look for tojson filter (https://jinja.palletsprojects.com/en/3.0.x/templates/#jinja-filters.tojson)
yeah, just use html input regex pattern, that's the easiest way unless you want to start writing JS
which may be necessary for more complex validation patterns
anyone know why the db commit is not working..?
it prints up to the current user stuff
but not to the search form
idk whats wrong with the commit
I am trying to render css and js on my flask server but it does not render it
How can i solve this?
how are you connecting your files?
<link rel="stylesheet" href="{{ url_for('static',filename='css/style.css') }}">
<script src="{{ url_for('static',filename='js/myscript.js') }}"></script>
is how i usually do them
for flask
Yeah, that's what i did.
I just need to validate a mail (\W|^)[\w.\-]{0,64}@(google)\.com(\W|$)
only for google.com for example.
does anyone know why it doesn't add the thing in the database?
that's the color of how usually should appear, but it turns into it just with syntax errors
i dunno why it's all the same color above
I suppose you could write a function in the models.py of the table you want to clear that just deletes all the entries.
please i am building a rest api server in python with fastapi and i have this error.
ImportError: cannot import name 'Entreprise' from partially initialized module 'schemas' (most likely due to a circular import) Can anyone help me?
Maybe you have a circular import?
yes... but i don't know how to fix it
Circular import means you're importing aa module into one file, but then that same file is trying to import from the original file so it is stuck in an importing loop
So look to see if you are importing one file into the other and then back again - if that makes sense
Sometimes you can be importing A into B, and then B into C, but C is imported into A, so it still creates a circle
You'd have to show relevant code for more help.
this is my __init__.py file where I import all the other files.
now in each file on /schemas I do from schemas import Pole, User or (...) as needed
it is in the schemas folder that I have this error not in the others
Anyone use selenium wire?
what are some of the main services that allow hosting of a web application?
i created a plain html file and it said it was free
000webhost com
or the free tier Oracle Cloud?
I'd encourage reading up about how time zones work in Django: https://docs.djangoproject.com/en/4.0/topics/i18n/timezones/
That said, I've been using Django for just under a year now and I'm finally starting to get clear about it. Your comment about the field in the model brings to mind the difference between a naive DateTime field and a timezone aware one. One approach I've taken is to use default=timezone.now() within the model itself.
However, where things get really interesting is understanding how timezone awareness plays out for an application that is used by users in different timezones. How you want to approach this will depend on your use cases; which is why there isn't one simple answer for you. For example, will you be using these DateTime fields for date calculations? How do you want DateTime fields to display to users?
The most accepted way is to keep timzones as UTC in the DB and then convert to the user's timezone as needed. You can do that on the front end with JS or on the backend, such as setting a timezone on a user profile (let them choose potentially), and then setting timeobject.now(tzinfo=users_timezone) before returning it.
in my opinion, i think you are importing Entreprise twice, line 4
You should try to remove "Entreprise" from line 4
from .entreprise import EntrepriseCreate, EntrepriseInDBBase
Need some help logging into and navigating a page. I was using selenium before but they've since added csrf tokens to the page and now I'm having a problem. Not sure how to grab to csrf for the current session and pass it with the driver
I can't get Flask auto reloading to work. It says it's reloading, but the template doesn't change
Like if I add text somewhere in the template and save, it doesn't show up until I refresh the page
Auto-reload is not auto-refresh of the page. The reload means the development server uses the new Flask instance.
You could use something like this for live reload
https://stackoverflow.com/questions/56972813/how-to-automate-browser-refresh-when-developing-an-flask-app-with-python
Is it possible in Flask to have a flash message
And in the html file, for an input text box
jinja to search for a regex and show a flask flash message if the regex is not matched?
is there any good resource for learning selinium for web scraping?
also, I heard scrapy is WAY faster but it doesn't load javascript so you can't interact with javascript components
is there a workaround or is selinium the only option in that case?
selenium is the best option if you would like to simulate javascript
you can use headless mode to speed things up a bit
As far as django tutorials go is there a difference between watching Sentdex or Corey Schafers?
Hey, im getting a ValueError (Cannot query ... must be 'user' instance) and im not sure how to resolve it.
@login_required
def watchlist(request):
params = {}
try:
get_wl = Watchlist.objects.get(wl_username=request.user)
params["wl_items"] = get_wl.wl_listing.all()
#print(get_wl.wl_listing.all())
except Watchlist.DoesNotExist:
pass
if request.method == "POST":
if request.POST.get("wl_btn") == "Add to Watchlist":
watchid = request.POST["watchid"]
listings = Listing.objects.get(id=int(watchid))
try:
get_lst = Watchlist.objects.get(wl_username=request.user) # Line that triggers the error
get_lst.wl_listing.add(listings)
except Watchlist.DoesNotExist:
user = Watchlist(wl_username=request.user)
user.save()
get_lst = Watchlist.objects.get(wl_username=user)
get_lst.wl_listing.add(listings)
return redirect("index")
return render(request, "auctions/watchlist.html", params)
my post model was working fine before now im getting this error => ```insert or update on table "Occupy_post" violates foreign key constraint "Occupy_post_occupier_id_27a10cf1_fk_Occupier_occupier_id"
DETAIL: Key (occupier_id)=(1) is not present in table "Occupier_occupier".
# a post can only have one user
#a post can only belong to one clique
# filters posts so only published posts are avaible in the home screen.
class PostObjects(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status = "posted")
options = (
('draft' , 'Draft'),
('posted' , 'Posted'),
)
clique = models.ForeignKey(Clique, on_delete=models.CASCADE, related_name='cliques', blank=False)
content = models.TextField(max_length=400,null=False, blank=False,)
caption = models.CharField(max_length=400,null=False, blank=False,)
posted = models.DateTimeField(default=timezone.now)
occupier = models.ForeignKey(Occupier, on_delete=models.CASCADE,related_name='clique_posts',default=1)
status = models.CharField(max_length=12, choices=options, default='posted')
objects = models.Manager() # default manager
postobjects = PostObjects() # custom manager
class Meta:
ordering = ('-posted',)
def __str__(self):
#returns caption
return self.caption`````
@merry merlin#web-development message
hello i wanna ask something, currently im working for discord bot website
i wanna shown user profile picture from a url i have, so i made:
<img src="{{ AvatarUrl }}" width="25px" height="25px" class="rounded-circle">
but i get
<img src="(unknown)" width="25px" height="25px" class="rounded-circle">
how to fix this?, AvatarUrl is https://cdn.discordapp.com/avatars/838640428060246046/0615fcf08cc119d886a90fae81e4d2fd.png?size=2048
hello everyone 🙂 noob here,
trying to understand javascript
do you guys know what's the difference between these three loops?
myObj = {
"color": "maroon",
"fruit": "durian",
"month": "april",
"nick name": "greg"
}
for (let key of Object.keys(myObj)) {
console.log(key, myObj[key]);
}
for (let key in myObj){
console.log(key, myObj[key])
}
Object.keys(myObj).forEach((key) => {
console.log(key, myObj[key])
})
My flask command is suddenly not working
this error pops up: 'flask' is not recognized as an internal or external command,
operable program or batch file.
I already added it to path
python and site packages
i even uninstalled and installed it
flask runs fine on my web-app but dosent work in command prompt
maybe it is installed on a venv?
// some code here
if (agent) {
// move the agent
console.log(input[i], input[i].move, input[i]["move"])
if (input[i].move) {
console.log(input[i], i)
let moveDirection = input[i]["move"];
// some code here as well
on the first console log it prints everything fine
but on the second input[i] and i become undefined
how can i solve it?
for (let i = 0; i < input.length; i++) {
let agent = this.getAgentById(input[i].id);
if (agent) {
// move the agent
console.log(input[i], input[i].move, input[i]["move"], i)
if (input[i].move) {
console.log(input, i)
let moveDirection = input[i]["move"];
// let moveDirection = [0,0]
let i = agent.i + moveDirection[0];
let j = agent.j + moveDirection[1];
if (i >= 0 && i < this.gridSize && j >= 0 && j < this.gridSize) {
this.moveAgent(agent, i, j);
}
}
// the rest
}
}
so heres more complete picture
Django
how do i validate unique constraints in serializers? I have this
models.UniqueConstraint(
fields=["time"],
condition=~models.Q(status="L"),
name="unique_not_cancel_time",
)
Agreed. And implementing timezones effectively through the project, particularly with numerous datetime fields, can prove interesting. I'm getting the hang of it, and with the latest project I think I have it. Testing across timezones will be the proof though. 🙂
!rule 9
Hi 👋
Did anyone tried to integrate the Paypal webhook with Django Rest Framework to accept payment?
I think the Paypal docs are messy and I have no idea what have to do as a back-end, so if anyone tried that before, please provide me with useful links/tutorial
Can I add uid to my model after the model has already been migrated ?
Django:
How can I use two different kind classes from an abstract class in the foreign Key?
has anyone had experience with websockets? and have you made a server/client combo?
could you show/tell me how you did it and
does anyone know how I can make a websocket server class?
I've done it with this for a hobby project: https://github.com/Pithikos/python-websocket-server
It doesn't have great SSL support though.
thank you so much!
ill have a see tomorrow
Guys, what program is recommended to building front-ends with python?
(or is that not even a thing?)
well you can do it with django templates but thats basicly just html with special tagging
Flask is very buggy in chrome, where it randomly doesn't import the style.css file while in firefox it seems to be working completely fine. Any ideas of whats wrong
What do u use to serve static files
U a supposed to use nginx for that
Nginx as reverse proxy to flask gunicorn.
Plus it serves static files
oh then how would you do that
yea ill try that thanks
I hab that why my hobby is Python lmao
And coffee too...drinking one rn

does anyone know how i would just extract this part of the text?
someone pls @ me if they know
Hey, sort of a stupid question but how do i create this "-----" in django? currently mine just automatically picks the first category until the user specifies
i want the default to be "-----" which isnt a category instead of "Toys"
I have an div tag which i want to apply a border, but it is getting applied to its padding as well!
So how can i apply a border only to the element and not its padding
can anyone help me with django/htmx/css issue I'm having??
< option value="" selected disabled hidden>——-</option>
I'm a big fan of https://anvil.works I used to do a lot of django and RoR stuff, but I won't be going back any time soon!
Hi all,
I work on an API with FastAPI which adds game cards entries to a mongoDB with file upload for front and back images of the game card.
Should I split the file upload and the create endpoint for creating a game card? The workflow would basically type all the infos into a form, add the images and create the card. But what is best practice for adding File Upload?
Is it better to split this into two api calls for error handling?
thanks 🙂
(Django)How can I get only the rest Api views in Django(static files?)? I want to share my API.
Thanks
damn, thats nice
Hey I created this in Flask, I want to display the progress while processing the uploaded file. is that possible with jinja2?
Not a real progress bar. If you know how long it's likely to take then you can fake it with some js
what are all the must know python technologies to work in a company that uses python programming language
Thank you
i want to migrate me removing a field of my models but i keep getting this error => ValueError: Field 'occupiers' expected a number but got ''.
#A clique can have many users.
#A clique can have many posts.
class CliqueObjects(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(level='public')
options = (
('private', 'Private'),
('public', 'Public')
)
name = models.CharField(max_length=200, null=False, blank=False,default='')
created_at = models.DateTimeField(auto_now_add=True)
occupation = models.CharField(max_length=90,null=False,blank=False,default='')
level = models.CharField(max_length=10, choices=options, default='public')
objects = models.Manager() # default manager
cliqueobjects = CliqueObjects #custom manager
def __str__(self):
return self.name ````
Hello! making an web app with Django. in Frontend trying to make buttons that can see only owner of Topic using Django Template Language.
{% block content %}
<div>
{% if user.username is topic.owner %}
{{ user.username }} is the owner of {{ topic }}
{% elif user.username == topic.owner %}
{{ user.username }} is the owner of {{ topic }}
{% else %}
{{ user.username }} is not the owner of {{ topic.owner }}
{% endif %}
{% if user.username == topic.owner %}
{% buttons %}
<a href="{% url 'learning_logs:new_entry' topic.id %}" class="btn btn-primary" role="button">Add new entry</a>
<a href="{% url 'learning_logs:delete_topic' topic.id%}" class="btn btn-danger" role="button">Delete Topic</a>
<a href="{% url 'learning_logs:change_public' topic.id %}" class="btn btn-outline-secondary" role="button">public {{ topic.public }}</a>
{% endbuttons %}
{% endif %}
</div>
{% for entry in entries %}
<div class="card mb-3">
<h4 class="card-header">
{{ entry.date_added|date:'M d, Y H:i' }} {# '|' фильтр применяющий дальше формат даты. !Регистр имеет значение #}
{% if user.username == topic.owner %}
<a href="{% url 'learning_logs:edit_entry' entry.id %}" class="btn btn-outline-warning btn-sm">edit entry</a>
<a href="{% url 'learning_logs:delete_entry' entry.id %}" class="btn btn-outline-danger btn-sm">delete entry</a>
{% endif %}
</h4>
<div class="card-body">
<p>{{ entry.text|linebreaks }}</p> {# linebreaks следит чтобы все разрывы текста присутствовали на самом деле #}
</div>
but its not works.
1 screenshot is how it works now
"""Тема изучаемая пользователем"""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
public = models.BooleanField(default=False)
def __str__(self):
"""Возвращает строковое представеление модели"""
return self.text```
Topic Model. User model is default to Django
OK. fixed it. im not sure. but since i refer in Topic model to User model, not to User.username, i should check
{% user == topic.owner %}
now it works
python ./manage.py compilemessages
---> Running in bb9b1dfa036a
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 244, in create
app_module = import_module(app_name)
File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'quotas'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute
django.setup()
File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate
app_config = AppConfig.create(entry)
File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 246, in create
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Cannot import 'quotas'. Check that 'gill.contrib.quotas.apps.QuotasConfig.name' is correct.
The command '/bin/sh -c python ./manage.py compilemessages' returned a non-zero code: 1
ERROR: Service 'worker' failed to build : Build failed
Migrating django from 3.0.8 to 3.2, I started to have random module import to fail. Any ideas what can be wrong? I checked already the name, looks fine.
from django.apps import AppConfig
class QuotasConfig(AppConfig):
name = 'quotas'
INSTALLED_APPS = (
'gill.contrib.quotas',
)
how do I redirect after returning response in flask?
Tried threading
RuntimeError: Attempted to generate a URL without the application context being pushed. This has to be executed when application context is available.
Traceback (most recent call last):
File "C:\Users\Documents\python sublime\b.py", line 2, in <module>
from selenium.webdriver.keys import Keys
ModuleNotFoundError: No module named 'selenium.webdriver.keys'
[Finished in 334ms]
how to solve this error
Was the module selenium.webdriver.Keys instead?
hello, what the best way to create a model of products that will have other models in relation with it ?
Update. The problem was in 3.2 breaking changes with AutoDiscovery stuff. I still did not get it. By disabling default=False behaiour in AppConfig, resolved the issue 🤷♂️
i'm working on a project(bugtracker) in django and was wondering if this was an alright 'app' structure for it?
project, ticket and users are ~~models ~~ apps and i'm not quite sure if base would be a good addition to merge them all together, since it's an app?
i also don't quite understand app in django, is it just a reusable module or is there anything more to it?
hello everyone 🙂 noob here,
do you guys know how to use React?
how do i loop through the contents of a list and put them in my jsx?
const listItems = [
"apple",
"banana",
"grapes",
"petchay",
"apardor"
]
function List(){
return(
<ul>
{listItems.map((li) => {
return (
<li>{li}</li>
)
})}
</ul>
)
}
this works but i get error saying please use prop key what
you only need to provide a key for every list item, react wants to be able to differentiate one list item from another if they change which is why it asks for that https://reactjs.org/docs/lists-and-keys.html#keys
ty keys are arbitrary? what are keys? lol
the link offers far better explanation 🙂
yes i'm reading now. it looks like how keys are with objects? so in my example.
function List(){
return(
<ul>
{listItems.map((li.actualItem) => {
return (
<li>{li.actualItem}</li>
)
})}
</ul>
)
}
?
nope lol
wait keys are supposed to be given as an attribute property to the element, and as a parameter to the function?
here we go this got rid of that error
function List(){
return(
<ul>
{listItems.map((li, text) => {
return (
<li key={text}>{li}</li>
)
})}
</ul>
)
}
not sure if im doing it right though
I'm using Flask with SQLAlchemy, when creating a user I want to create some sort of object which stores all their settings from the program (not the user credentials), what would be the best way to accomplish this?
I thought that if I were to put that in the user class the class would get to big once the application expands
Maybe create another separate settings class?
Does anyone know a good way to solve this?
i think what you want is a new table with the user settings and use one-to-many relationship using the your initial user primary key?
yes I think
you can also just use the same table for now and move the columns to a new table in the future. if it deoes become needed
yeah, SQL is a bit hard for me
but storing in the same table would be the easiest route
on the other hand maybe doing it good the first time would prevent a lot of work down the road
if i'm understanding this correctly: you want to be able to store some user 'settings' in the server/SQL
if that is the case then a relationship between two tables might be what you're looking for, like bregue suggested
something like this
one thing i've learned from SQL tables is:
Normalize it until it hurts, Denormalize it until it works 🤣
can flask build a very good quality website?
can flask replace javascript + css? thank you
oh hey im using that rn

anyone up for 10 mn ?
If I wanted to implement a DOM api for python
Something which you could work with using the same function calls, the same structure
Walk the same walk as with any standard vanilla javascript, in the important ways
Where do I start?
What I've done so far is implement a Node class, inheriting from an EventTarget class
And then numerous subclasses of Node including Element, CData (Text, Comment, Instruction, Doctype), Document, and Attr
A NodeList class to represent a Node's childNodes attribute and an Element's children attribute
And a NamedNodeList class to contain the values of an element's DOM attributes
And I think that's it. Does all that check out?
how can i make my flask website do this?
I was working with Django/Wagtail when I ran into this error message
'NoneType' object has no attribute '_inc_path'
Does anybody know how to fix this?
!
use js for that
and sends the data by rest api
ohh.... idk anything about js... any way that it can be done with flask or other python framework?
for that prompt? no ig.. u need to use js for those prompts
:'/
ah damn. thanks
:>
How to redirect with delay from backend in general? instead of using Js
which framework you're using?
I'm using Flask
ok idk.. nvm 😂 ||(if it was django.. i could have been of some help.. :"/ )||
let's wait for someone who knows .. :")
sure whyn't
I can switch my entire code to Django if u can help me
i can help, but won't spoonfeed
:")
for redirect in django
u can use
!d django.shortcuts.redirect
redirect(to, *args, permanent=False, **kwargs)```
Returns an [`HttpResponseRedirect`](https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpResponseRedirect "django.http.HttpResponseRedirect") to the appropriate URL for the arguments passed.
The arguments could be:
• A model: the model’s [`get_absolute_url()`](https://docs.djangoproject.com/en/stable/ref/models/instances/#django.db.models.Model.get_absolute_url "django.db.models.Model.get_absolute_url") function will be called.
• A view name, possibly with arguments: [`reverse()`](https://docs.djangoproject.com/en/stable/ref/urlresolvers/#django.urls.reverse "django.urls.reverse") will be used to reverse-resolve the name.
• An absolute or relative URL, which will be used as-is for the redirect location.
By default issues a temporary redirect; pass `permanent=True` to issue a permanent redirect.
yes ^
will that work if I have already returned response and run this in threaded process to redirect?
returned response as in? redirect is redirect.. i didn't get that part 🤔
Let me explain what I mean to ask
lets say I have a background process awaits to be accomplish,
So how could I redirect after its completed without response timeout.
That's what I'm looking for
🤔 well.. it's like in django.. u make function for redirecting ( to a website) or rendering (any html file) so inside that function u can do whatever u want
but at this point.. i'm not sure if that function can be async.. cuz i never tired to do it.. lemme search on google... lol
wait I'll send u screen shot
alright
I need help on design decisions, I am making a resume builder webapp with free and paid templates, my questions is should I be generating pdf on server side and send to frontend or just send the html and css of the template to frontend and let them handle the conversion? (Converting html to pdf seems like very heavy task to be done on the backend but I think I can do it asynchronously using celery and send the user an email with the pdf attachment) what do you suggest?
don't be discouraged, that is not a prompt made by js, it is the browsers built in authentication prompt
it is usually configured directly in the configuration for the web server or using an .htaccess file in a content directory
but there is a way to do it using flask (in your case, other frameworks can of course also do it) as well using: https://flask-httpauth.readthedocs.io/en/latest/
the most common type of http authentication is the one called basic authentication, one of the most impotent things to remember with this is that it is very insecure if not used over TLS/SSL (https:// urls)
you can read more about http authentication works here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication
from the above link:
Security of basic authentication
As the user ID and password are passed over the network as clear text (it is base64 encoded, but base64 is a reversible encoding), the basic authentication scheme is not secure. HTTPS/TLS should be used with basic authentication. Without these additional security enhancements, basic authentication should not be used to protect sensitive or valuable information.
@gentle jasper and @native tide, you probably also want to check http authentication mentioned above
you can't redirect using the http protocol after you already sent other data in response to a request as redirecting that way is a 3xx http response
if you have not closed the html <head> tag yet you can use html redirect to accomplish what you want
if that option isn't feasible due to that restriction you could go with redirecting using javascript anywhere in the page
for information on all the three above mentioned methods: https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections
Any of yall who can help in web scrapping data?
I am new to python
I want to provide the content of a log file to a webpage, with it updating the new lines as they get added (I do have access to the process that logs into the file, so I could do it directly if possible) but preferably without the webpage refreshing and removing selections/scrolling back up/down etc..
Does anyone know of a way how I could potentially do this?
I've been searching but haven't really found anything.. 
Ping if you have an idea thanks
depending on what you want to do the requests and beautifulsoup4 libraries my be of interest to you
yes
a requests lib tutorial may help
I want to scrap nba stats
I need to scrap data from the NBA site and then code it in such a way so that I can see any players stats from any year but i cant do that 😢
https://realpython.com/beautiful-soup-web-scraper-python/ may fit your bill as a starting point
Ty
I'm attempting to upload a file, process it, and then download it. To do this, I submitted a POST request to the server at the '/upload' route, and the server should redirect to the download page after processing the uploaded file.
However, the difficulty is that it experiences response timeouts as a result of the processing large file.
I tried multithreading, but even with that, you can only respond to a request once, so you can't redirect once you have respond a request in a separate process Thread.
How can I redirect as soon as the uploaded file has been processed?
if you got a long running processing task, it's more common to run the task as a separate process instead, and have it scheduled using some task/job runner (dramatiq, celery?) ... on the download page you might then instead see the progress of the process. Or maybe get redirect first to a progress page, and once done, get redirected further to the download page....
redirect first to a progress page, and once done, get redirected further to the download page
Could you please clarify this part? It may appear straightforward, but I'm not sure I understand the procedure.
the way it's done. when you upload a file, you start a background process and immediately redirect to a progress page. usually those job runners have some kind of ID that represent the job that is running in the background, so you would pass that ID along to the progress page.
once there, you can regularly (javascript?) check with the job id, if the task is finished or not. and once finished, have the browser redirect to the downloads page (with javascript as well, probably).
there are other ways of course.
Server-sent events?
uhm possibly? that would require websockets probably, but still javascript on the frontend
you could do without javascript, and just start the job after upload, store the job id in database or something, immediately redirect to the download page, and list all finished files and still-in-progress files... simple F5 would then update the list
Thanks a lot for this info!
Hello guys
I have simple question
I use VSC and Django FM
Someone give me advice witch theme is the best for this FM? thx
you can't immediately redirect the client as you need to wait for the file to upload unless you start a background thread on the browser side using javascript
for a nice user experience you probably want to use javascript for the upload
Flask or fastAPI for webdev newbie? quick answer:)
Flask of course for newbie
Django for mid
FastAPI for expert ;b
Ok, some arguments then 😄
Flask and Django are from Sync ecosystem of python. Sync is easier.
FastAPI is from async.
Flask is microframework that will train you from zero doing everything on its own. A bit more healthy for beginners I think
Django and FastAPI both frameworks of battery included approach, A lot of stuff out of the box. Better to try microframework like Flask first before diving into them. U will have better understanding what u use then
FastAPI doesn't have to be async and often isn't
Hmm, I started with FastAPI and it feels quite comfortable to work with
If it's a good for for your project, then start with FastAPI
Then go with it then 😉 FastAPI looks 20% cooler
Quart is an async implementation of Flask.
real project use FastAPI or Django I think
Flask is a bit useless because.... it has no... advantages
There's a lot of legacy flask applications because it used to be the easiest way to spin up a quick rest API, but not any more really
I tried it. It is ugly thing that should NEVER be used. It is a bastard between Flask and Async ecosystem. With half of libraries from Flask, and half from Quart. It is not a framework. It is Frankenstein!!! https://www.spelshop.be/7659-large_default/frankenstein.jpg
I saw many job offers for django devs but from my IT insides large companies move to FastAPI these days 🙂
Just faster to deploy
Are you trolling... WTF. Flask is bit useless, Quart should Never be used really?
Quart should never be used.
It has really hard compatibility within its own libraries
they aren't really correlated with each other
Authors assume the person would use compatibility mode with Flask
and it works... and not works. Just lucky chance
I have never had such issues
Flask just has no advantages in comparison to Django or FastAPI.
I am serious 😉
that's the only reason
anything flask has, Django or FastAPI can do better
And flask logo is ugly
It has one really big advantage, it is simple and basic for when your goal isn't to build beast of an application.
Seriously!
we need beasts. preferably built yesterday
We always strive for perfection
thanks
Is there some guide on how do I set up quart? Because I think I set it up wrongly
have mercy upon yourself. Use Flask or FastAPI
😄
FastAPI is fine, try it, it's modern and cool, and devs get many money for it
Ain't Quart just async Flask?
I thought FastAPI is for different purposes than Quart?
Quart is failed attempt to make async Flask. Which you don't need nowdays anyway. Quart was invented because Flask made slow work in the past to introduce asynciness.
But Flask 2.0 is ASYNC already. And yeah FastAPI is Async which is more mature anyway, so if u wish async, use FastAPI
The flask tutorial that I'm using rn feels so confusing lol; like how do I get that file path??? and why am I running the webserver out of the venv lol https://flask.palletsprojects.com/en/2.1.x/tutorial/
Ouh I see. I thought Flask has always been non-async and quart is async. Idk about Fastapi and I don't think I wanna move from Flask to it lol. I'll just stick to flask then
@hard whale Just wanted to troll around with webservers lol
Does it have the same stuff as flask? Like render_template and stuff
Mostly yes
Also if I'm following this, do I just pip install flask out of my venv https://flask.palletsprojects.com/en/2.1.x/tutorial/
I know that big companies use either django or fastapy
But I'm too lazy to switch aaaaa
so if you want to get a job, fastapi might be a better choice
Hold up let me see if fastapi has a better tutorial
fastapi looks 99% the same
fastapi has a lovely tutorial
trust me
i started with flash, couldn't run a server for 3 days
tried fastapi, server is up in 30 min
20 of those 30 min i was scratching my butt and making myself a cup of tea
Ah yes my struggle
That must be one itchy butt
I'm a newbie and I don't know all the stuff under the hood but some large international banks use fastapi for their apps
and they say "oh you know django, cool you suffered much, enjoy fastapi now coz we need to build and deploy FAST"
there must be some core reason why they moved to fastAPi in the end
For more tutorials, subscribe to this channel and follow me:
Buy Me a Coffee: https://buymeacoffee.com/parttimelarry
Twitter: https://twitter.com/PartTimeLarry
Website: https://hackingthemarkets.com
Source Code: https://github.com/hackingthemarkets
It will take time to understand how all this work BUT at least it will work
Ahh I see. I always thought flask is the most common one lol
Ah thanks for that
Tho I'm using the fastapi article tutorial thing
Uh huh I'll keep that in mind
It is lovely
Now i'm struggling with my app creating db in venv instead of project folder
what are the most popular hosting services for web apps?
Django question:
I have two models (Chat and User).
Chat and User have a Many-To-Many relationship.
How can I check if a users exists to add them to the Relationship in Chat? What Response is possible if it doesn't exists?
objects.filter(blah blah).exists()
if yeah, then add it
it will return False lol
Yeah I know that. But how can I tell the user (via. rest api) that the user didn't exist
with a correct status code etc.
I have users in a Chat object.
If I try to use for user in data['users']: it'll give me a key error bcs users is not in the request. How can I validate that users is in the json req
try .json()
like
data.json()['users']
for a flask web application, do sqlite databases work in aws elastic beanstalk?
No - it wouldn't because you get "new" instances of your app spinning up and down which would mean you lose the information
you need the database to exist on some remote server
my web app takes up the whole screen of a small screen, but only half of the screen of a larger screen
how do i write some code so that it takes up the same proportion of the screen on any device?
im fucking stupid 💀
First off, hello, if this needs to be moved to another channel please let me know
I'm trying to deploy my webapp to azure and i ran into some trouble on my db migration. I'm following this tutorial https://docs.microsoft.com/en-us/azure/app-service/tutorial-python-postgresql-app?tabs=flask%2Cwindows%2Cvscode-aztools%2Cterminal-bash%2Cazure-portal-access%2Cvscode-aztools-deploy%2Cdeploy-instructions-azportal%2Cdeploy-instructions--zip-azcli%2Cdeploy-instructions-curl-bash
and i got to step seven pretty easily but for some reason it's telling me it cannot import frontend(frontend.py is my flaskapp but idk if that is something that is causing the issue) and then it's telling me that there is no such command as db. If anyone could help me out then that'd be great 🙂
Also, including the current issue and an issue i had earlier with flask_app not being defined(i think i fixed it with an export)export FLASK_APP=frontend.py
also, this is the command i'm using to do the db migration flask db init
or is my understanding of the db migration tutorial wrong and do i have to look up another way to deploy my flask app to azure?
try to rename your frontend.py into app.py
flask is pretty sensitive about filenames and folder structure
okay, I renamed it and am deploying again. hopefully it works fine this time
i'm following the tutorial loosely if that makes a difference? I have my own code and project that i'm trying to upload. I'm just following along the steps needed to bring my stuff online
the code you are using should not matter.
@timber jungle it was saying the same thing but this time it could not import "app"
could this be the issue?
did you set the env variable to the new name of the file?
when i ssh into my server i navigated into the proper directory with my app.py and exported it export FLASK_APP=app.py so i think it should be okay but I'll reupload and try again with that.
btw when i tried what i first said in this message it gave me a lot of errors and this was the last thing that was actually legible sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not translate host name "test-server" to address: Name or service not known
you will have to solve every error encountered.
It may be a one of the reasons why it fails.
Anyone used GraphQL with Django/python and seen that a query is called once but the associated resolvers in Django are actually run 3 or 4 times? react + apollo/graphql/graphene + django
I can't seem to track down how that's happening.
you should be able to fix that issue with css and using relative units for sizing things of the page, and you probably want to set maximum and minimum sizes as well
Does anyone know why Flask's Blueprints.. are called blueprints?
i make new models and my django migrations wont apply for some reason ?
Depends on the library you're using i guess
What do you mean?
depends on graphql library you're using
graphene_django
I'm actually just realizing too that some of my resolvers are running without them being called on the FE.
I called one query just now, ran it correctly, but another query also ran (according to django) without signaling in my chrome debug tools that it was called (no console logging)
Resolvers under the same query class don't automatically run together right? Or can one trigger another?
how to set maximum per day user can fill the slot and from where i need to start and how to set functions user can fill up to 10 times then the slot is locked. thank you
class BookingSettings(models.Model):
# General
booking_enable = models.BooleanField(default=True)
confirmation_required = models.BooleanField(default=True)
# Date
disable_weekend = models.BooleanField(default=True)
available_booking_months = models.IntegerField(default=1, help_text="if 2, user can only book booking for next two months.")
max_booking_per_day = models.IntegerField(null=True, blank=True)
# Time
start_time = models.TimeField()
end_time = models.TimeField()
period_of_each_booking = models.CharField(max_length=3, default="30", choices=BOOKING_PERIOD, help_text="How long each booking take.")
max_booking_per_time = models.IntegerField(default=1, help_text="how much booking can be book for each time.")
This is my view
Has anyone had this error? I'm doing an automation with selenium and python, and the 'ul' variable works in the interactive mode of the terminal, but in the code it doesn't.
WebDriverError@chrome://remote/content/shared/webdriver/Errors.jsm:183:5
NoSuchElementError@chrome://remote/content/shared/webdriver/Errors.jsm:395:5
element.find/</<@chrome://remote/content/marionette/element.js:300:16
HELP
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
» type-hint
» venv
» voice-verification
» windows-path
» with
» xy-problem
» ytdl
» zip
trying to migrate and keep this error => django.db.utils.ProgrammingError: relation "Occupy_clique" already exists
Hello there! I'm trying to make a Flask-based API hosted on Heroku. I have a global method that creates responses and it looks the following way:
def response(body = None, code = ResponseCode.SUCCESS, message = "") -> flask.Response:
if message == "":
if code == 200:
message = "Success"
elif code == 404:
message = "Not Found"
else:
message = message
response = jsonify(body)
response.status_code = code;
response.headers.add_header('message', message)
print('Responsing with:\nMessage: ' + str(message) + '\nCode: ' + str(code) + '\nBody: ' + str(response.data) + '\n')
return response
And so, when I have to handle some request I do the following:
@api.post('/some-route')
def some_route():
# Do some stuff here
return response({'some_key': 'some_value', ... })
Such thing causes H17 error on Heroku when responding.
Here is the description of H17 error in detail: https://devcenter.heroku.com/articles/error-codes#h17-poorly-formatted-http-response
Does anyone know if there is a way to run PyCharm over web like VSCode?
VSCode is written in TypeScript which is then transpiled to JavaScript which can both run in the browser and on the desktop using Electron
PyCharm on the other hand is written mainly in Java, which will be a lot more work to port over to be able to run it on the client side within the browser nowadays (java applets are dead since quite a while back, and good riddance for that)
I have models Resume and Education, and education have a fk to resume, I need some suggestions for the urls. I have the urls for list and detail view for resume - /resumes/, /resumes/<int:resume_pk>/ and for education list i have /resumes/<int:resume_pk>/educations/, what url do you suggest for the education detail view? i can do /resumes/<int:resume_pk>/educations/<int:education_pk>/ and then take the education pk to get the education object, here resume_pk is unnecessary and may make confusion, or i could just remove it and now the url is not as obvious as before, /resumes/educations/<int:education_pk>/
is anybody here good at typescript?
If I want to set up a website where the user can upload an excel file and Python script will run to process that data to return another excel file, how can I do that?
there are a lot to do
why do you need this?
hi guys not sure if this is the right place but could someone explain what this means
[<Element h3 at 0x1034a7a10>]
im trying to scrape the text of this element
but get this on print
<ClassName element at position in memory>
ahhh ok
i dont suppose you know how i can get the text from that element?
probably something like element.text
!code
ebay = r.get(f'https://www.ebay.co.uk/sch/i.html?_from=R40&_nkw=ps5&_sacat=139971&rt=nc&LH_Sold=1&LH_Complete=1')
tree = html.fromstring(ebay.content)
sales = tree.xpath('//*[@id="srp-river-results"]/ul/li[2]/div/div[2]/a/h3')
print(sales.text)
print(sales.text)
AttributeError: 'list' object has no attribute 'text'
that is my code and that is the error i get below
lmk if this is the wrong channel as idk if web scraping counts as web development
sales is a list, in other words tree.xpath returned a list, and my guess is that there multiple elements on the page that match your xpath criteria. Print sales without .text and see what you get and go from there.
thank you, oh yeah sorry when i print without .text i get [<Element h3 at 0x101957dd0>]
is there another way to do it without xpath that wouldnt run into this issue
with .text i get error
It isn't an issue. It seems that tree.xpath returns a list whether there is one or many elements found. In your case all you need to do is print(sales[0].text) and you will get the result you want.
you are an absolute legend, thank you SO much
been doing this for hours
trying to google and couldnt find
Ayo guys anyone has experience with SQLModel for FastAPI? I heard it collapses pydantic and sqlalchemy into same one file aka easyer to work with sql
Is it really that good?
I use 2 separate files now and sintax differences are a bit confusing
Idk about legend. If you want a more robust solution. Instead of just print element [0], iterate through the sales list.
for sale in sales:
print(sale.text)
This will give you the same result, but if you did have many elements it would print each of them.
thank you!
for some reason i get list index out of range sometimes
it might be a problem with the site when im changing product tbf
is there any other way to get information without the xpath
as i need a different xpath depending on the user input
or possibly just take a screenshot of the whole page that the user inputs tbf
List index out of range means that the you are trying to index an element that doesn't exists. So if you list has one element and you my_list[1] it will throw that error. If you are getting that error with [0] it means that you are getting an empty list.
If you use my second solution,for sale in sales. then this wont be a problem, it simply wont print anything. Another solution is to first test the list to make sure it is not empty:
if len(sales) > 0:
print(sales[0])
else:
print("nothing found")
ahhh ok thank you
sweet
is it possible to take a screenshot, send it and then delete it straight after?
idk
ok nws, thank you anyway youve saved me for a lot of this project
My pleasure!
Is there a way to run a python file (on the pc running the flask server) through a button on my website?
What does the file do?
Simplest way assuming it is its own program and not a function:
import subprocess
import sys
subprocess.run([sys.executable, "/path/to/script", *args])
Well, I don't have any particular function there right now. Although I've tried to just open a picture to check if I even can start a file through a button, but it runs each time I save the python, and not when I click the button. If that makes sense?
I know the python side of it, but I don't how to or where to activate the python file from lets say a button click.
you mean from html?
Yes, both from html and in the flask part of the server python file (if there is anything I need to fix there).
<button onclick="runFile">Run</button>
<script>
async function runFile(event) {
event.target.disabled = true;
try {
await fetch("/runfile", {method: "POST"});
} catch (e) {
alert(e);
} finally {
event.target.disabled = false;
}
}
</script>
in flask
@app.post("/runfile")
def run_file():
subprocess.run(...)
the only part of the function that's really needed is fetch
the rest is boilerplate and can be excluded if you don't want to handle errors or double clicking
I'm going to disagree with this approach. The js/ajax approach is fine, but I server side I would handle it much differently. First, you should have the server respond back with a some kind of a message "success" "fail" message so that the user get's feed back as to whether the function call was successful.
I was doing a very simple example.
Second I wouldn't use subprocess. I would import the function into the flask file and call it from flask directly.
And yes, using a function is always better.
I get that, but in my opinion there are place to cut corners and providing a success feedback is not one of them, as it is simple enough to do. All you need is for your end point to return a jsonify'ed response with {"success": True} after the process returns (or False).
I'm also lazy, so there's that.
The work with respect to response is handling the it on the client side. But the lazy way would be to simply show an alert.
Which is what I did. But it only alerts if there was a network error
<script>
async function runFile(event) {
event.target.disabled = true;
fetch("/runfile", {method: "POST"})
.then( resp => {
if(resp.success){
alert("Success that worked")
} else {
alert("Something went wrong with the python script")
}
})
.catch (e => console.err("error:", e);
}
</script>
can anyone help me with this error ? => django.db.utils.ProgrammingError: table "Occupy_clique_occupiers" does not exist
I copied your code and forget to remove the async, but either way it works. I prefer using promise.then().catch().
when is it better to use a web builder like wordpress, compared to full coding?
I'm working on a flask api but I want to use the api for other people not on my network how can I make it so the python script uses my IP address to fullfill the task?
you new to use 0.0.0.0 host ip
Then it uses available inner IP dhcp adress so you could find it localaly, like in wifi
To through it available OUTER ( you need to got to your router and forward this ip in and port ) so anyone could see it by you're router IP and forwarded port
anyway to change the from in django when user select something without using jquery ?
or the more suitable way to do it drys
I’m wanna set up an interface for my optimization program where the user can simply put in the data without needing to know python
When all u need is simple landing page without any special functionality.
Or when you build super ordinary product, like electronic shop for a really cheap client
Basically... As long as word press has required functionality to make the stuff, u a fine.
If u stepped out of its limits... Then better to be not using it
How about htmx
api_names = ["/predict",'/predict_solubility','/predict_two','/predict_solubility_json']
@app.get(api_names[0])
async def predict(background_tasks: BackgroundTasks,solute,solvent):
background_tasks.add_task(predict_dum.get(0),solute,solvent)
return {'success'}
@app.get(api_names[1])
async def post():
return {'result': response}
@app.get(api_names[2])
async def predict_two(background_tasks: BackgroundTasks,solute):
background_tasks.add_task(predict_dum.get(1),solute)
return {'success'}
@app.get(api_names[3])
async def post():
return {'result': attach_drug_name()}
I am having a fastapi which does predictions on two end points and returns response. The background tasks were implemented using fastapi workers. Now how can i shift it to celery workers.
Try using fastapi
It is very neat, simple and fast
anyone has some tutorial to split backend and frontend for beginners?
I have no idea how to do that, but looks like something funto try.
Mhm and how do I make it use my network
instead of 127.0.0.1
you need find you local IP address and then use that instead of 127.0.0.1
@native tide
if you are on windows, try the command ipconfig
'title' : forms.TextInput(widgets=attrs={'class':'form-control', 'placeholder' : 'Title'}),
'description' : forms.Textarea(attrs={'class':'form-control','placeholder' : 'Description'}),
'category' : forms.CharField(attrs={'class':'form-control','placeholder' : 'Choose Category'}),
'bid' : forms.FloatField(attrs={'class':'form-control','placeholder' : 'Place your bid here...'}),
'url' : forms.URLField(attrs={'class':'form-control','placeholder' : 'Paste your url here...'}),
}
I want to add placeholder but this error is coming
init() got an unexpected keyword argument 'attrs'
I'm not sure wym
What is easier implemented with FastAPI (optionally SQLModel):
- Let cliend request data from db via API
- Just scrape this data from web page displaying the very same table
?
Webscraping tables must be tricky
WTF...
- let client request data from Backend app endpoint, that returns data in json format. The Backend app makes request to db.
hey guys
anyone can help me with django ?
Which is 1. actually
well yeah. But it was a bit strangely formulated.
clarified more precisely
Coz I'm noob ;P
class pForm(ModelForm):
class Meta:
model = personalInfo
fields = (
"religion",)
widget={
"relagion": forms.TextInput(
attrs={"class": "form-control"}
}
reChoice = (
("select_one", "Select one"),
("islam", "Islam"),
("cristian", "Cristian"),
("hindu", "Hindu"),
)
religion = models.CharField(
"Religion", choices=reChoice, default="select_one", max_length=50
)
But yes :)
I am having fun. Migrate a django app from 3.0.8 to 3.2 version, which has 4000+ tests. and 420 out of them are breaking during migration.
It is all wrong because there is no Zen Buddhism
in html using {{ form|crispy }}.. but dropdown being just text input instead of dropdown.. can anyone help ?
I heard dinosaurs used django and that's why they died
I'm sure they did
anyway can anyone help me please.. dying here with problems and limitation 😦
I wish I could bro but i myself a big noob :)
Im having troubles with django urls. for some reason my main urls cant detect my other 2nd apps urls. it worked fine for the first one
Django is so complicated 😫
Django is pain 🙂
i love it tho. gets my brain going
God bless fastapi
Doesn't get brain going but doesn't even require you to have one to do your stuff
@stark mesa can you help me with this one please and give us the code in urls.py (main one)
alright
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('store.urls', namespace='store')),
path('basket/', include("basket.urls", namespace='basket')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
lets make coding great again
been tryna solvee this for almost an hour
i even tried this as a test if it would fix it
path('basket/', include('django.contrib.auth.urls')),
path('basket/', include("basket.urls", namespace='basket')),
if i cant fix this imma just put it on hold and just move onto another
type_queryset = qs.annotate(
type=Value(type, output_field=CharField()),
date=Case(
When(previous_date=None,
then=F('next_date')),
default=(F('previous_date') + (F('next_date') - F('previous_date'))/2)
)
)
Expression contains mixed types: DateTimeField, DurationField. You must set output_field.
how to fix errors like that?
'date': Case(
When(
previous_date=None,
then=ExpressionWrapper(F('next_date'), output_field=DateTimeField())
),
default=ExpressionWrapper(F('previous_date') +
ExpressionWrapper(
ExpressionWrapper(
F('next_date') - F('previous_date'),
output_field=DurationField()
) / 2, output_field=DurationField()
), output_field=DateTimeField()
)
),
Obviously somehow like this. But I have somewhere error 🤔
Lets think step by step.
next_date is a DateTime
previous_date is Datetime
their substraction is TimeDelta
/2 = still TimeDelta
previous_date + TimeDelta = DateTimeField. Looks like everything is correct, but it is wrong 🤔
how to debug it
step by step 😉
I don't get it
Case(
When(
previous_date=None,
then=F('next_date')
),
default=F('next_date')
)
this works
Case(
When(
previous_date=None,
then=F('next_date')
),
default=ExpressionWrapper(F('next_date'), output_field=DateTimeField())
)
this does not work
it is supposed to be working. It is the same F expression but with specified DateTimeField type...
nvm. I solved it + multiple other cases, xD stuck in another one
is there a way to save multiple form data in one table ?
from multiple html forms to html tables or database tables?
you probably need to tell us a little bit more about what you want to do and an example of the type of data
i have a db with a bunch of entries that i want to use in an autofill function
so like if a user types into the search bar- "pok"
under the search bar i want like the top 3 alike things pop up under the search bar. If anyone has a suggestion on how or what to look at to do this i'd greatly appreciate it
Guuuys, strange question
What's safer: Django web framework or just FastApi?
When using Flask, is it easier to use a MySQL database or a SQLite database?
Depends
Example: You can use SQLAlchemy, so api looks the same, using you SQLite or MySql driver
If you use sqlalchemy, how would you deploy to heroku?
i have heard that you need something called postgres
PostgreSQL is relation database
You can use it as SQLAlchemy as driver instead of MySql
Also it`s very not recommended to deploy sqlite db on heroku
Django web framework i think
or better, I use django
What do you mean by "safer" ?
Yeah.. I mean strange question
"safer" about number of possible vulnerabilities
It depends on you really
Also, vulns made by beginner
Most vulnerabilities come with authentication, authorization and input validation
I personally would not recommend Django for building APIs
django has a lot more code in the project and is also much older and has many more users then fastapi, so it might be very hard and unfair to compare them
but if you search the internet for known "security vulnerabilities" for each of the two projects you'll find many more and many times more severe vulnerabilities for django then fastapi
Thanks for answering :>
Django is just old at this moment, if you're building api I would use fastapi
django has a lot of developers working on it and they are very transparent about their security vulnerabilities, which is a good thing, check out https://docs.djangoproject.com/en/4.0/releases/security/
Only advantage of using Django for me is built in authentication
And Django orm is just not very good
and here is the same for fastapi https://github.com/tiangolo/fastapi/security/advisories
i would say fastapi has a better security record (so far) 😆
as long as that list is indeed complete and they are as transparent about them as the django team is, we can only hope
Hi guys , i got a customer that wants e-commerce website for one usage (concert ticket selling website) , i couldnt gave him a price , what do you think about it ? How much that costs generally
also consider that django has been around soon to be 17 years, while fastapi only is little over 3 years old
Fastapi just also has smaller footprint: no built-in orm, authentication, etc
exactly, much smaller code base and thous a smaller vulnerability cross-section, even though that is not a guaranty for more secure code on it's own
There's just much less potential risks
but on the other hand you have to bring in all those missing pieces from somewhere else and then you have to trust that code too
Some services might not even need authentication, it could be handled by third party
and that those projects are as vigilant about fixing security bugs in a timely manner and that the project has enough eyes on it to find those vulnerabilities
Also i can't stress enough about how bad django orm is 😦
of course, but what i meant was that you need to bring the missing pieces that you do need your self
I need a form like this.. I made a model and form .. but I can't split cuz all I know is {{ form.ap_s }} {{ form.as_table }} so can't split like that form.. so I made 1 model but 4 form with that.. it allowed me to split the form but it save differently 😦 I need it on one table
from email.policy import default
from logging import PlaceHolder
from django.forms import ModelForm
from django import forms
from .models import personalInfo
class fForm(ModelForm):
class Meta:
model = personalInfo
fields = (
"fName",
"fcNum",
"fOccu",
"fEmail",
"mName",
"mcNum",
"mOccu",
"mEmail",
)
class pForm(ModelForm):
class Meta:
model = personalInfo
fields = (
"inProgram",
"shift",
"session",
"section",
"sName",
"cNum",
"email",
"gender",
"bCert",
"image",
"religion",
"doBirth",
"pAds",
"bGroup",
"nationality",
"quota",
)
class e1Form(ModelForm):
class Meta:
model = personalInfo
fields = (
"eTitle1",
"board1",
"eGroup1",
"bRoll1",
"eResult1",
"pYear1",
"insName1",
)```
import calendar
from calendar import HTMLCalendar, month_name
from datetime import datetime
from django.shortcuts import render
from django.urls import is_valid_path
from .forms import pForm, fForm, e1Form, e2Form, d1Form, d2Form
from .models import personalInfo
from django.http import HttpResponseRedirect
def addmission(request):
submitted = False
if request.method == "POST":
form = pForm(request.POST, request.FILES)
form2 = fForm(request.POST)
form3 = e1Form(request.POST)
form4 = e2Form(request.POST)
form5 = d1Form(request.POST)
form6 = d2Form(request.POST)
if (
form.is_valid()
& form2.is_valid()
& form3.is_valid()
& form4.is_valid()
& form5.is_valid()
& form6.is_valid()
):
form.save()
form2.save()
form3.save()
form4.save()
form5.save()
form6.save()
return HttpResponseRedirect("/addmission?submitted=True")
else:
form = pForm
form2 = fForm
form3 = e1Form
form4 = e2Form
form5 = d1Form
form6 = d2Form
if "submitted" in request.GET:
submitted = True
return render(
request,
"addmission.html",
{
"form": form,
"form2": form2,
"form3": form3,
"form4": form4,
"form5": form5,
"form6": form6,
"submitted": submitted,
},
)
Would gladly replace django orm with sqlalchemy, authentication is not that hard to get right either
Can anyone help me with this one please... I need this so bad 😦
With flask, is it possible to specify some default options when using flask run?
@nimble berry Sorry I'm bad at telling problem.. hope it'll give you some idea
e.g. ```py
app.run(
debug=True,
extra_files=[
Path("pages").glob(".md"),
"settings.toml",
],
)
i still don't really understand what you are trying to achieve and the exact problem you are facing
and full disclosure: i'm not very good at django, never really cared for it
To be honest I can't understand Django either ... Its easy to learn new language than learning everything about django .. yea its makes things easier but need to know lot of django things .. I just made 4 split html form and want to add their data in single table... They have 1 table option.. but sake of customization I need 4
https://paste.pythondiscord.com/luhoyasewu can you help me with some different code i want to work out average pixel whiteness of image. my code i wrote i think the library doesnt support transparency, i have transparency in my image
Is it possible to convert a flask web app into a desktop app?
like an equivalent of electron js
a desktop app with the same ui and working in the same way as a flask web app
and you want it standalone without being dependent on an external web server?
standalone would be ideal but i dont think thats possible
but the same ui, with api requests would be fine
Well, I had a problem before, thought it was a ports issue but seems like its one with quart. I have a help channel opened, anyone mind looking at it? #help-pancakes
don't know if it fits your bill, and i should add that i have never used it myself, but there is something called flaskwebgui https://github.com/ClimenteA/flaskwebgui
Hi I'm having some issues using fastapi with prisma client python. I'm trying to use prisma model like this:
@app.post("/add_temp")
async def add_temp(temp: Temp):
await db.add_temp(temp)
return {"msg": "ok"}
the problem is that fast api expects the model Temp to have a field called id even though it's supposed to be generated.
someone help me sum all pixel colours?
u sure it's id is autoincrement or smth ?
hey guys
I deployed my flask app to heroku, but when I tried to access it for the first time, I got the application message that my page could not be served. In the terminal I got at=error code=H10 desc="App crashed" method=GET path="/" with status=503 and such status means that the server runs properly but can't be served at this time
does that really mean that I should just wait or what? is there a problem in my code? because my application runs with no problems locally. I've already waited 15 minutes and heroku still can't serve my page. Does anyone know what is going on?
restarting heroku did not help
my Procfile also looks correctly (no unnsecessary spacing) etc
this is my prisma.schema https://github.com/MichalUSER/weather_app_server_py/blob/prisma/prisma/schema.prisma
I think it's supposed to work but maybe I'm making some mistake
I don't think you're supposed to use database models in fastapi endpoints
what am I supposed to use theb
Create a schema model
because this is how I do it with expressjs in typescript
class PostSchema(BaseModel):
id: str
title: str
content: str
class PostCreateSchema(BaseModel):
title: str
content: str
It's not, your api schema shouldn't depends on your database models
the point of Prisma is to have a prisma.schema file that has models which are converted into classes that I can use normally
Well, but these are still your database models
You might need to change your database structure, your schema on the other hand shouldn't change
I see
Or you risk taking down prod 🙂
Because your clients (frontend, other services) used different schema
anyways thanks for your help I will look into it tomorrow
hello is there a server for django framework?
Is there any library or something that I can use for my flask app that I can use for autofill suggestions?
Twitter typeahead or jquery autocomplete.
Hello may I ask what license would you guys use for your website ?
I'm trying to pick a license but I don't know which one to choose because there are so many/
Okay, so like
Am I crazy?
Or is the DOM as implemented in Javascript fucking bonkers?
Example: The Document object is a node, except can't be/have a parent and can't be/have any children. All it gets, really, is inheriting from EventTarget by proxy
Window is NOT a node, even though its relationship to the rest of the program is pretty much the same as for Document, but window DOES inherit EventTarget directly
Attribute inherits from Node also, even though its basically just a tuple consisting of a name and a value (and of course, all the extra bagage it inherits from Node)
And yet a dozen other component classes of Element DONT inherit from Node
I am having a fast API that does ml predictions and uses celery for task queue.
prediction code
response = {}
async def predictions(solute, solvent):
m = Chem.MolFromSmiles(solute,sanitize=False)
n = Chem.MolFromSmiles(solvent,sanitize=False)
mol = Chem.MolFromSmiles(solute)
solute = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(solvent)
solvent = Chem.MolToSmiles(mol)
interaction_map_one = torch.trunc(interaction_map)
response["interaction_map"] = (interaction_map_one.detach().numpy()).tolist()
response["predictions"] = delta_g.item()
and my function in worker.py
from model.model import predictions, response
@celery.task(name='predictions')
def predictions(solute, solvent):
return {'result': response}
and main.py where i create the celery task
@app.get(api_names[0])
async def predict(solute,solvent):
task = predictions.delay(solute,solvent)
return JSONResponse({'task_id': task.id})
Actually, I am migrating from fast API background tasks to celery and facing problems with returning responses. When I am running it is giving an empty dictionary celery which means it's not running the prediction. But I don't know where I am doing wrong. If you can check the below picture you will understand what I am saying.
I am guessing I have done some wrong in the worker.py but not sure what it is.
what are you expecting to get back as a result from the call after you have migrated to celery?
remember that the celery job will probably not have run yet when you send the client the response, so you can't really reply with any result, only something like a job id that they can then poll for at another endpoint later in a loop with a pause in between each try and then break out of the loop when that endpoint with that job id returns something meaningful
I agree with @serene prawn, separation of concerns between your database and your API is important. Currently you can automatically generate additional pydantic models with only certain fields, make certain fields optional or required and point relational fields to another model. The only feature that is missing is renaming fields.
and how can I do that
An auto-generated and fully type-safe database client
I've also opened a feature request to support renaming fields, https://github.com/RobertCraigie/prisma-client-py/issues/367
Yeah that works too, the benefit of using Prisma's built in support for partial models is that you don't have to redefine the types
And if you don't care what fields are in the model, you just want non-relational fields only you can easily do that too without having to update all your models
yeah I'm trying to rewrite my prisma typescript express server in python so I was a little disappointed when I had to redefine the types again
yeah I was in a similar situation and was annoyed that I had to redefine the types, that's why I added partial model generation :)
also do you know if there is a OR keyword in prisma python? Because I couldn't find it
like I can do this in normal prisma:
return await prisma.temp.findMany({
where: {
OR: [
{
"d": { "in": nowDays },
"m": new Date().getMonth() + 1
},
{
"d": { "in": beforeDays },
"m": weekAgo.getMonth() + 1
}
]
}
});
lunarvim (neovim) at the moment
I'm running the pyright language server
I should be using pylsp as well I know
my bad
Ah I was just about to recommend that
although I'm not sure if they work well together
because pylance in vs code has to be a little different than pyright I think
Are you getting autocomplete for Prisma Python queries?
yeah I am
Great :)
I know some people struggled to get that setup so I just wanted to make sure you had it setup
It's arguably the best feature imo
yeah it's really good
Let me know if you have any more questions :)
I don't think I do so thanks for your help 🙂
actually I may have one question @solid meadow, is there a way to ommit the #type: ignore so pyright doesn't complain about id being None as seen here:
async def add_last_temp(self, temp: TempClass):
last_temp = await LastTemp.prisma().find_first()
if last_temp is None:
await LastTemp.prisma().create(data=jsonable_encoder(temp))
return
await LastTemp.prisma().update(where={'id': last_temp.id}, data=jsonable_encoder(temp)) #type: ignore
What does your LastTemp model look like in the schema?
If it's like ```prisma
model LastTemp {
id String? @id
}
Then you've marked the id field as optional which means you could run into a situation where last_temp.id is actually None
You could either handle that case by raising an error or update your model so that the id field isn't optional
guy's what u think about rpa developer
oh ok but last_temp can be None because it's a find query
Yeah that's right
Hey, I have a Django Rest API endpoint that takes some data + image as an input, I'm trying to test this endpoint but I face a problem with sending an image
serializer.py
class CreatePackageSerializer(serializers.Serializer):
workshop_id = serializers.IntegerField()
title = serializers.CharField(max_length=550)
price = serializers.FloatField()
image = serializers.ImageField()
and sending data like this by Pytest
from PIL import Image
img = Image.new(mode="RGB", size=(200, 200))
data = {
'workshop_id': 1,
'title': 'Package Title',
'price': 33,
'image': img
}
so drf gives my this error
AssertionError: assert [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]
so, my question is how I can send the image as a file?
this is more js then python but idk whare to ask cause no one answers me
i want to build extension when someone clicks on it runs a js code on the website the user is in, can someone help me please?
I can't help you but maybe ask in some django discord server
although I don't think they have an official discord server but there is the forum https://forum.djangoproject.com/
This is surprisingly difficult, but possible. My suggestion for the first step would be to find a tutorial via Google or look at some of the official Chrome extension examples
does someone know how can I get and save a photo that user as uploaded in flask?
without flaskForms if possible
request.files?
If they're submitting a form it should just be a post request with the find file found there
do I need to pass anything in it?
I get this
The key isn't the filename
It's whatever the form key is I think
The docs are here
Are you using Django?
If you want to run it from your page without refreshing it, you should look into setting up a request via ajax. This sends a request to your server and then you can use the returned data/response.
If you don't care about it refreshing, you shouldn't need javascript.
complete beginner here. What is the best way to implement that kind of animation
As my site-background till the user picks a choice on where to go?
Hello. I'm very new to web development and programming in general. I was wondering what is the typical workflow when using django or other python frameworks for building projects. For instance, I heard that its a good practice to work with django or other python projects in a virtual environment, but im confused how that would play out when using github. Say If I made a web app using django under a virtual environment, so i also have to upload the files of the venv to github? What's the norm when it comes to this things? (I am new, so try to help me understand please)
You don't have to upload your venv files to github, only your dependency list
I would try something like poetry which uses venv under the hood
Can anyone guide me how to host JustPy website? I used Pythonanywhere for flask but it doesnt support justpy i cant seem to find anywhere. I want to share with others not just localhost
In simple words i want to share my justpy project with friends
So they can test some functions for me
you can either match the black color through a screenshot and then color picker it and use the hex value
You've got a number of concepts jumbled up. And I get it...when I started I was very lost.
You can program with Python. Python has a lot of flexibility in the ways it can be used (use cases). When you program in Python you can create a virtual environment. This creates a safe space, or rather, an independent space where different tools you use (libraries) can be installed and offer you more potential and power. Python is such a well-used language that there are many, many tools (libraries) that many people have built that do many things.
Django is one such tool. It is a web development framework that, like Flask, allows you develop web applications. If you really want a web application that offers enterprise level administration and security, Django is a great place to start. If you want a simple website, Flask is recommended as a better starting point than Django in some ways, particularly because working out how web servers work is a whole layer of complexity when new.
GitHub is a tool that is a version control system. In other words, every time you update your program (in a github repository) git (the tool behind github) will track the changes, down to the individual characters. This is really helpful because software engineering is hard. When you build a web application in Django, for example, you'll be working with the presentation layer (how web pages appear), manipulating the application layer (with lots of logic, that will in effect allow you to build workflow) and building/using a database to work with data.
What is the norm? There are so many flavours of norm that there is no norm. I'd suggest thinking about a problem you'd like solve. Maybe it's a problem that can be broken down into a number of different problems. Then I'd learn how to program with Python.
thanks
Yo guys hope y'all are doing good!
My Problem:
I am trying to store a SQL query in SQLite in a variable so I can use it to show it on a Flask Website
My Code:
import sqlite3
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/results")
def results():
conn = sqlite3.connect("Database\database.sqlite")
database = conn.execute('''SELECT * FROM twitch_data''')
return render_template("result.html", content= database)
app.run()
HTML:
<!DOCTYPE html>
<html>
<body>
<p1>
{{content}}
</p1>
</body>
</html>
Can anyone tell me what is the appropriate way to store a SQLite query in a variable?
i wasnt sure if i had to use Available Help Channels or this channel
so i have sent it in both #help-bread n here
hope it's not an issue
Css file not supported in pycharm. Please help how to solve this
can you use modelserializer for nested serializer?
I have 2 models A and B and B have fk to A, i have model serializer for both and want to just include a list of related B in A's model serializer. can i just use the B model serializer to nest it in A? like this?
class B(serializers.ModelSerializers):
...
class A(serializers.ModelSerializers):
...
list_of_b = B(source="b_set.all", read_only=True, many=True)
hi guys, i kindly need your help, i can't seem to serve my static files whatsoever and i'm terruble at explaining
elaborate?
like while deploying or something?
i'm trying to center some text in a html table, the css looks like this
.tablee + td{
text-align: center;
}```
But it doesn't do anything, if i just do something like this it works, can someone help me ?
```css
td{
text-align: center;
}```
hey guys i have a question, I am creating a website using django and i want to create a desktop version for it in future so how would i make it interact with the database in my web application?
Hello. I have a problem with Django rest framework.
ViewSet has get_queryset which aggregates one big queryset with a lot of data.
one of the fields named organized_id is present in the returned objects
But it is not recognized as field which I could use to order_by/ordering.
what could be the problem? Perhaps I could make somehow the field recognized
make sure you are using the right selector - https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator.
Django has an ORM that communicates with the database. You should check out a few tutorials.
What do you mean it's not recognized? There an error?
I mean that i get error when trying to order_by this field in queryset
django.core.exceptions.FieldError: Cannot resolve keyword 'organizer_id' into field. Choices are: bla bla bla
so far I was able to make a trick of
bla bla bla are the other fields?
yeah
Do you need to declare the field somewhere before using it?
like admin.py you declare the fields included
annotate(
organizer_id=OuterRef('organizer_id'),
)
if I annotate by OuterRef
I can order_by this field then
but the query breaks later because OuterRef field has no declared is_summary thing
def EventRefundsViewSet
ordering_fields = ('organizer_id', 'name')
ordering = ('organizer_id', 'name')
I need this field declared for Django Rest Framework ViewSet in order to have working ordering, for a paginated view
the main magic happens in this ViewSet in function
def get_queryset(self):
where the queryset is formed. There is the problem, as this field is incorrectly queried. Not fully formed into the query columns
Ok, so whenever I run into that error with REST or GQL, it's because I didn't include it in the fields that have to be declared.
but it looks like ordering_fields is where you do that
The problem appears because queryset is formed using custom made multidb_objects.prefertch_related thing
it is a bit of complicated
I am trying to find just a hack around it in order for the field being recognized
This was on SO: "Did you enable cursor pagination in your settings?"
REST_FRAMEWORK = {
...
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination',
...
}```
too bad organizer_id=F('organizer_id'), is not working, the field is not recognized error again)
yes it is present.
another custom made thingy
Well, if you're hacking it, then something must be setup incorrectly. If it's an ID field, I would think it should work without issue.
This application is huge as fuck (5000 tests)
I wish to do in some way at least
What if you remove 'name' from ordering?
Does it work with just the organization_id?
nah. it works only if ordering by name, or if not ordering at all
Can you order by the id before you get the set?
Where the original queryset is formed
sure
I dont get it. It gives me nothing 😉
I think we can both agree I solved your problem 100%. 😄
It is already midnight here,I can agree with anything at this point 🤣
guys, do you know if type attribute is necessary for <source> tag?
or it is optional
Does no one know how?
Hi everyone. I have inherited an Angular application that was generated by Angular CLI version 9.0.2. I have the following in my Dockerfile: https://bpa.st/UFIA. When I run docker compose up frontend --build, I see the following error: https://bpa.st/7BXQ Is there a way to upgrade the Angular dependencies to newer ones then manually update the code to use new Angular API (for lack of a better term)? Thanks.
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
on that page is a link to a big list of Discords
there's definitely JS ones on there, and probably an Angular specific one
Hi. Yes I did take a look but the invite links of the JS one seem dead. Also there wasn't any that was Angular focused.
how I can enable ssl on django
YES!
I have managed to integrate Select2 ( search in dropdown ) with a list in python 😄
It is working beautifully.
<div class="rs-select2 js-select-simple select2-search">
<select class="" name="projectid" required>
<option value="" selected disabled>Select a Project</option>
{% for element in gcpprojects %}
<option value="{{element}}"> {{element}}</option>
{% endfor %}
</select>
I would like to apply <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> to only a section of a webpage, with the rest being in bootstrap. How can I do this?
Looks like most of the classes are prefixed with w3-
I would just copy what you need and make your own css file
Most of what isn't prefixed with w3 is normalize, which bootstrap provides as well.
Other than that, it sets the default font and sizing for html, body, and h elements
If i have a container / wrapper. How can i make some elements go outside of it?
position: absolute; ?
i will try, thanks
hello everyone
how can i fix this error ??
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.
I created a script that must run with crontab in a django folder but when I import the models to insert data I have an error.
has anyone here used gradio?: https://gradio.app/
Build & share machine learning apps delightfully.
this is because you need to setup or prepare a django environment - you might want to check custom commands https://docs.djangoproject.com/en/4.0/howto/custom-management-commands/
still you might need to define where your settings are
Hey Guys,
Looking for some guidance.
So I am creating a web app using django as the backend that tracks the stats of nft project prices.
I would like to know the best way to load this db , If I should be using the post from the api or loading directly with mysql.connector or another direct method. I'm worried about the slugs and the timestamp when loading from with python
Also I would like to show charts of the prices changes how can I accomplish that with django and the front end? Looking up data from 3 days and comparing it to now.
This will be a prob website so optimization will need to be in mind
How could I connect a django app running on an aws server to a domain I bought?
Is there a way to import HTML into another HTML file? For example, I have a base.html file and I want to have the content in a separate HTML file named content.html.
hi i am doing an assignment and im getting these errors
this is my code btw
import {courseType} from "/home/udit-waghulde/Assignment_3/services/Course/course-service";
import {instructorType} from "/home/udit-waghulde/Assignment_3/services/Instructor/instructor-service";
import {Instructor} from "/home/udit-waghulde/Assignment_3/services/Instructor/Interface/instructor-interface";
export class Course implements courseType {
CourseDetailsByInstructor: any;
course: any;
CourseDetailsByCid(CID: string): courseType{
let item: any = this.course.find((item) =>item.CID == CID);
return item;
}
static find(_arg0: (item: any) => boolean): any {
throw new Error("Method not implemented.");
}
private CourseDetailsByInstructors(Email: string, info: any){
if (info[Email] !== item2[Email]){
info[IID] = item2[IID];
}
this.course.push(info);
};
let course = [
{
CID: "215e77ee-ba6d-486f-95ce-0e0c0fb4b919",
Title: "Programming In Javascript",
IID: "185e77ee-ba6d-486f-95ce-0e0c0fb4b919",
},
{
CID: "225e77ee-ba6d-486f-95ce-0e0c0fb4b919",
Title: "Structural Analysis",
IID: "195e77ee-ba6d-486f-95ce-0e0c0fb4b919",
},
{
CID: "235e77ee-ba6d-486f-95ce-0e0c0fb4b919",
Title: "Power Electronics",
IID: "205e77ee-ba6d-486f-95ce-0e0c0fb4b919",
},
];
function Email(Email: any): any {
throw new Error("Function not implemented.");
}
is there somewhere i can go to talk to other poor devs that got stuck creating microsoft canvas/power apps? im having some growing pains trying to trick microsoft dataverse and the app builder into functioning like real development tools.
I have a technology field in my django model asset_inventory_active
These are some of the values of the field
I want to get the count of each technology, those separated by commas also
Example- count for Nginx- 2, because the last field contains Nginx tech and the first field also contains Nginx tech
How do I separate all tech if they separated by commas, and get their count also
top_techs = asset_inventory_active.objects.values('technology').annotate(tech_count=Count('technology')).order_by('-tech_count')[:5]
Right now I m getting the top 5 tech like this, but this doesn't work properly because it considers Nginx,Ubuntu as a single tech
I want them to treat as differently
i'm trying to implement jquery autocomplete in my flask app and was wondering if I could use a python variable that i passed into my html page as a var in some script
<script>
$(document).ready(function() {
var some={{content}}
var tags = [
"Washington", "Cincinnati",
"Dubai", "Dublin", "Colombo",
"Culcutta"
];
$('#hello').autocomplete({
source : {{content}},
select : showResult,
focus : showResult,
change :showResult
})
function showResult(event, ui) {
$('#cityName').text(ui.item.label)
}
});
/script>
var some is what i want to happen but it doesn't like it currently
is there a better way to do it?
:incoming_envelope: :ok_hand: applied mute to @earnest dagger until <t:1650525486:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
Thank you
What are the pros and cons of using Nameko as a micro service web framework?
What are the use cases of django channels ? (other than chat app)
Hi! I'm mainly a backend developer, but I want to build a web application. I have been using FastAPI earlier without a database connection, which was awesome. However, this web application is more complex and should include a database. Is Django probably a better choice since its opinionated (which I like)?
A big community is great but I would rather use new and improved technology, if it's well documented and on the rise.
Also, I've been thinking of using a modern frontend framework, like ReactJS or Svelte.
I built a website where you can practice your programming skills by working on weekly projects to improve your skills. All skill levels welcome! https://www.devjam.org/. This may be useful to some of you who want to try putting your skills to the test against others.
Hey, whats up with livereload dying when I update Python?
It works fine if I change the template, but it dies if I try to update any Python files
Am I doing something stupid here
Guys I'm building a blockchain app using typescript and express i just started building it should I switch to python and flask or python and django (NOTE: My app only uses REST)
just curious why do you want to replace your current stack?
Hello im making a Post model using django and want the post to have as many images as the user wants to post, how to implement this ?
tried typing the option (many=True) like in the django rest framework but it look like django doesnt have one
You can have a model that contains an image and a ForeignKey that points to a specific post
but that means only one image for a post right?
No
You can create many image models with the ForeignKey pointing to a specific Post
i dont understand
hows this different from just leaving the image field inside the Post model
oooh
i get it
lol
thanks
if anyone has other ways of doing this let me know about it
@mental summit this way right?
Looks good
Hey guys new to the server and django for that matter.. I used the built in auth & auth models provided. However, when I make my own model (Member) I can't call all results and display them. (works for user model). Do I have to specify something as I've imported the member class.
I've detailed it and put my code up there, any help or suggestions would be great
trying to darkmode a page which works for the main homepage however on this site for some reason the <body> is only registered as that tiny top section. any ideas why. site is running flask btw and the production site is apache2
Hello there, I have a very weird bug. Every time I save this file, and only this file. It gets completely emptied. Also my code doesn't recognise the € character, it shows as a �. Does anyone know how to fix this?
Problem fixed, not using the € symbol apparently
Weird @queen horizon
Maybe using the html symbol for Euro might work? They are called html entities afaik
Well that works
But it's kinda stupid, because in the files my friend made the € works fine
so purely theoretically.. how bad is loading flask variable "content" in this instance with a lot of entries(maybe 80k max of just names) and using it in jquery autocomplete?..
@app.route("/test", methods=["POST", "GET"])
def test():
if request.method == "GET":
languages = ["C++", "Python", "PHP", "Java", "C", "Ruby",
"R", "C#", "Dart", "Fortran", "Pascal", "Javascript","joe","Joestar","Jotaro","john"]
return render_template("testing.html",content=languages)
elif request.method == "POST":
user=request.form["em"]
return render_template("testing.html",content=user)
<script>
$(document).ready(function() {
var some=JSON.parse('{{content|tojson}}');
$('#hello').autocomplete({
source : some,
select : showResult,
focus : showResult,
change :showResult
})
function showResult(event, ui) {
$('#cityName').text(ui.item.label)
}
});
</script>```
i want to do autocomplete searches off of a database of names i have and that's why i ask
Like could I potentially do this
Names= db.execute(SELECT * FROM table_name)
return render_template("testing.html",content=names)```
Without much consequences?
(Also, sorry for the syntax/ formatting typing from mobile atm)
For flask, Is there a way I could specify a version variable in my app.py and use it in my base.html without passing the version variable in every render_template statement? I understand that I could just hard code the value into the html, but I want my app.py to handle the versioning so it shows on GitHub
Guys i need to check when a button which is normally hidden is displayed in a website and if it is displayed then click it, there is a way?
Java script is best for web development
the website isn't mine so 
Depending on specifics, selenium, a Chrome extension, or just a simple js script pasted into the console is probably the way forward
how to make flask_basicauth only get password
cuz flask_basicauth needs a user and a password, i want it to only need a password
i would prefer using selenium, when the button is pressed a new page is displayed so i need my code to connect that page too and find the button again (his name will change a bit) and then press it again when it is visible
Well selenium has a pretty reasonable python interface. I've not used it but I don't think it's too difficult to get set up. That's definitely where I'd recommend looking
i'm starting documenting
i keep getting this error in my django app => django.db.utils.IntegrityError: insert or update on table "authtoken_token" violates foreign key constraint "authtoken_token_user_id_35299eff_fk"
DETAIL: Key (user_id)=(1) is not present in table "Occupier_occupier".
just prompting for a password with out even displaying the username field can't be done with what is built-in to the browsers by default
using your own code you could just ignore what ever is filled in to the username field and a blank username should probably work as well in that case and just check the password
if you don't want to display the username field you have to roll your own and you could probably make something similar using javascript for the prompting of the password
that said, i would highly advice against any of those solutions for more reasons than i care to enumerate here
you can go and check what was written on the subject many years ago even if the question isn't 100% a match and it has been a while most of the reasons holds true still
https://security.stackexchange.com/questions/20072/using-only-password-to-authenticate-user-no-username-field
https://security.stackexchange.com/questions/2384/why-do-we-authenticate-by-prompting-a-user-to-enter-both-username-and-password
Django started life soon to be 17 years ago, it's really big and used by a huge community
FastAPI is soon to be only 3,5 years, it might not have as big of a community [yet] but might fit in with what you termed as "new and improved technology" and "on the rise"
how do I resolve ERROR for site owner: Invalid key type google recaptcha v3 error on django
my captcha settings seems good
pls help
hi, guys
need a help with django: i have a custom implemented django user inherited from AbstractBaseUser and i need to create roles like student, teacher and etc with extended fields
can you share links, articles or something else to implement this thing? checked veryacademy on youtube, but don't think that it is for me
how do you make a bootstrap nav bar, which has this feature?: when you click on a page, there should be an indication that you are on the services page.
Add a class or ID called active and give it the desired CSS elements and on each page, add the active class/ID
is there a way to do this with a layout.html instead of having to include the nav bar in every page?
help #help-pretzel
Depends on what you're using to generate the HTML. If you're using something like Flask or Django, you can inherit templates and override blocks. So all the different pages can inherit a base template that is common to all pages (e.g. the nav bar), and individual pages can override relevant blocks - the body of the page for example
try asking your specific questions instead
@nimble berry I'm trying to apply a bootstrap template to my table
it selects all div elements which has a article class
And?
@nimble berry I m not sure how to do
If a flask/django web app is hosted on a vps service like linode/digital ocean, would a sqlite3 database still work?
can u help
it depends on the service, but generally for vps the answer is yes, you need presistent storage that you can trust and if they offer backups of that storage it's even better
then you have providers like heroku that don't offer vps service, ther the answer is instead generally no as you don't have access to persistent storage, there you are recommending to use a external database like a PostgreSQL server or as a service that they can provide
well, heroku apps have postgresql add-ons tho
idk why i'm telling but ... lol nvm
i was talking about jessicaM
sorry
well in your case rndpkt already answered
but still telling
that if u host on heroku u will get postgresl-add on @stable bear
you'll just have to look on the web about how to host your django app & configure its db with your app
that's all
where else r u planning to host?
:")
i would personally recommend heroku if u want to go for free
since i'm not aware of any free vps...
so yeah
:")
it has its own limitations tho.
GCP has an always free tire, with their e2-micro you'll have free hours to last you a howl month if you only run one of them, or you can run a few hundred for much shorter time
there are limitations on amount of storage and network traffic and such as well that you need to manage to keep it free
Anyone know of a way I can pass a bunch of db results to my html page? I'm doing this in flask as well
you know how to access a db from your flask web app?
Yeah?
I'm using sqlalchemy so I'm making an engine object and then doing like db.execute(SELECT * FROM table_name) to get results
Well that gets me a pointer i believe
@nimble berry
if you are going to use an ORM (like sqlalchemy) you'll be working with models and stuff
so i've finished with my personal project, i'm just looking for tips on decoration / presentation...
if someone has any spare time, could they go through and check my code out to point out a few things, or redecorate the file entirely?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
if anyone is willing to, could they dm me
It seems that Flask jsonify doesn't preserver the order of the input dict. Is there away to ensure that the dict in is in the same order as json string that it returns?
Otherwise I suppose I could simply use json.dumps to create a string and the set up a manual json response (ie: by setting response headers).
Can you elaborate on that?
what does your relevant code look like so far?
After some investigation, it appears that this is not exclusively an issue with Flask but also an issue on the browser side, in that the browser appears to be sorting the keys of the json object. So I'm thinking my only choice will be to use json.dumps server side and send the response as text as opposed to json.
I'm not sure what you would gather from the code.
return jsonify(my_dict)
```my_dict where the keys are in no specific order, but for which the order must be preserved.
So I tried sending the response text/plain and that solves the problem. Here is the solution in code in case anyone is curious:
json_str = json.dumps(my_dict)
response = await make_response( #await because I'm using Quart not Flask.
json_str,
{ "Content-Type": "text/plain; charset=utf-8" }
)
return response
The response header on the client side is as above (as expected) and the browser displays the string as is without parsing the JSON into an object first.
yeah, that is an issue with json, order shouldn't be relevant according to the spec
but that doesn't mean you can't force your software to generate it ordered
Yup, fortunately for my needs a string representation is fine
you should still be able to use jsonify() by setting this to False https://flask.palletsprojects.com/en/1.0.x/config/#JSON_SORT_KEYS
but json.dumps() should do the job as well
Yes, I saw that and it is true but there still is a problem with the browser, if you send it JSON it will parse it and sort it. I need the result to be same on the server as on the client side, every time, a string provides that.
yeah, but at least you can choose how to implement it server side
but is json the best fit for this if you need to preserve order?
Json is standard used for this, so I don't really have a choice.
ah, okay
can someone run through my code and tidy everything up?
Where is it?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I don't really find any issues. It looks pretty good. The only change I would make is instead of
If not x:
return False
return True
You can do return x
in those cases, for example 'emails'
the if not is testing to see whether there have been any emails fetched or not
if i was to return emails it'd be giving me the emails fetched, when all I want is to check if it exists
is there anything i can do to make it look more presentable?
By presentable do you mean easy to read?
i guess so yes
I would say having your classes and routes in different files
Have each file's functionality clearly defined
thats a good idea, i'll work on that
the classes and subclasses, i've definitely not worked them right - are u able to run me through how i could better them?
Why would you have User inherit from Database is there anything in the database that the user needs?
nope, i forgot to remove it
it's declared in __init__ of user now
self.database = Database()
In this case instead of checking if the array has any values it's better to just do
email_exists = cursor.execute(f'SELECT * FROM users WHERE email = \'{email}\' AND confirmed = \'TRUE\'') is not None
return email_exists
just tested it, that throws True even if it doesn't exist
because the cursor returns something like [()] if it doesn't exist
which isn't None
I'm guessing its because cursor.execute returns an object. You could add .first_or_none() to make sure it returns a workable values
to the cursor?
What framework are you using?
Yes?
hello everyone 🙂 noob here,
you guys know css?
im trying to copy this guy's flex but i cant get it to work the same way
his are centered
while mine are stuck to the side
any ideas?
* {
box-sizing: border-box;
}
body {
margin: 0;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
min-height: 100vh;
display: flex;
align-items: center;
font-family: 'Inter', sans-serif;
background-color: whitesmoke;
}
.contacts {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 40px;
}
.contact-card{
flex-basis: 225px;
box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.25);
border-radius: 10px;
display: flex;
flex-direction: column;
padding: 13px;
padding-bottom: 20px;
background-color: white;
}
.contact-card > img {
width: 100%;
height: auto;
align-self: center;
border-radius: 5px;
object-fit: cover;
}
.contact-card > h3 {
font-weight: 700;
font-size: 18px;
}
.info-group {
display: flex;
align-items: center;
}
.info-group > img {
height: 11px;
margin-right: 8px;
}
.info-group > p {
margin-block: 3px;
font-size: 12px;
color: #2B283A;
}
figured it out it was just a typo on the classnames
alright, thanks for the info :")
i got this error from instance = self.Meta.model(**validated_data) this line of code how can i solve it ?
anyone know how to solve this => ImportError: cannot import name 'Clique' from partially initialized module 'Occupy.models' (most likely due to a circular import)
You have circular import between your models, use string identifier to import it
I believe it's app_name.ModelName
string indentifier ?
ohh calm ill try that
And remove your import for this model too
thanks
Depends on what you mean by "make"
You can use python for backend, if you need something complex then only choice for your frontend is JavaScript
ok
hey guys is there any discord server based on only web-development?
I have udemy full webdevlopment and DSA also course with life time access
At just Rs 250 only
Hurry up
If any one interested can dm me
@open forum(look at the message above)
💀
!rule 6
please help at #help-cheese thank you.
is there a way to edit html before render_templating it, using flask?
Jinja may be a way
yee, googling led me to directly calling jinja, but i dont wanna open the template file on each request
i wanna use the caching part (i hope render_template caches things)
Hey there please help #help-cheese sorry for messaging in between a conversation.
caching thing is implemented at another level. Don't care too much about it
We host flask application as Gunicorn + Nginx.
Nginx as reverse proxy + it hosts your static files
Nginx at the same time can handle caching rules, for certain urls which you specify (or all of them)
+Cloudflare with its CDN is yet another more high leveled caching mechanism
ohh, so i use html as static content 🤔
+If you wish to have caching at the level of framework....
...you can cache inside of Flask with using Redis key-value in memory database
rittt
as you can see. There are many means to cache stuff 😉
i mean... you render html in flask as...
...compilated result of Jinja framework
with insertion of different CSS/JS files into it
CSS/JS files will be cached by Nginx / Cloudflare rules, client side caching can be applied to it
the rendering of the page itself?
you can cache it with Nginx or with Redis (or with Cloudflare too)
your ability to cache it, depends on what type of content it has
totally goin nginx file system thingy
If the page is purely static in content? you can cache it agressively at CDN / Client side way
if the content is changing only with query params? You can cache at nginx level (probably with CDN too)
If the content is fully dynamic? You can cache with Nginx requests to JSON endpoints, or you can cache dynamic data in Redis
many means to cache stuff
Nginx can cache for you at server side side, intercepting requests before they reach framework and giving cached result in advance
or Nginx can cache for you by adding Client side caching rules headers to the files. Which will make stuff cached in the client browser
yeah, im already using nginx for serving stuff, will just add another rule to expose another port interally that can serve my html files
good.
Read the free Nginx cookbook from O'reilly
to know what you can do with Nginx
get a hang of Cloudflare service, for the most powerful CDN caching, it is easy
and optionally learn using Python Redis library, in order to use key-value db
tysm
list-style: none;
}
.menu-up a {
text-decoration: none;
color: white;
}
.menu-up ul {
display: flex;
justify-content: space-evenly;
width: 60%;
background-color: black;
margin: 0 auto;
}
.menu-up {
text-align: center;
position: fixed;
top: 0;
left: 0;
background-color: black;
width: 100%;
border-bottom: 0.5px solid white;
z-index: 20;
}``` i don't want it to be display: flex but something else but when i for example chage it to display: inline-block it goes like this