#web-development
2 messages ยท Page 169 of 1
Cool, I heard abotu graphQl but never used it before
and what's Apollo
never heard of that
Apollo is a client that helps to cache data from the server, so you can deliver user requests even faster by reducing server requests.
oooh it sounds great
Well, apollo has a client, and also a server and other tools.
But I just use the client with next.
That would make your web more fast and better SEO
lol
Yea I used react before but I learnt Next and It's very similar to react but when I tried it I compared the performance of react and next and tbh next was faster
and it was a basic web just to compare those two
I believe next is something we gonna see more in the future
isn't nextjs also just react? They should be similar
I see
It's like React the future
Anyone know any good Hugo themes?
is django as backend and reactjs for frontend possible? would it be a good combination for web app as a stack?
ye that's fine
cool. thanks
Yes - really good industry standard combination.
yes I'm new to js. you mean django + angular?
yes. thank you!
NextJS (TS) + Django + Docker, killer combo
ye
Hi guys, why if a try to load media files in deployment with debug = False my media files are not loaded?
i'm using django
Agreed
Some of Next's features are amazing, and when paired with the power of Django, you can make some really nice things
trying to use selenium for webscraping - but I'm using a lot of time.sleep(). It feels really hacky. Is that normal?
for?
there are APIs for waiting until something loads
which is what I think you want
I am using front-end framework vue js. I want client api key and client secret type structure for another vendor to use my apis.
what are the things I absolutely must need inside a heroku requirements.txt file for Flask?
I keep on getting a H10 app crashed error.... but my Procfile and wsgi.py looks good
on my requirements.txt file I have psycopg2, gunicorn, all the Flask stuff...
do I need certifi or chardet or requests?
also my wsgi.py file is
from app import create_app
app = create_app()```
which might be a little confusing, could this be a problem?
yo guys, i recently learned javascript and html, and i already knew python, i was wondering if i could connect python with html and make a website which is controled by python as a back hand
yes, totally possible
frameworks Flask, Django and many others are an option for that
Hey guys, in a django rest app, I would like to extract metadata from a file after an upload, and save it in an object fields. Which way would you recommend ? custom upload handler or drf upload parser ?
Why do I get a syntax error on posting = request.data.postings here?
context = [
posting = request.data.postings,
unsafe_email = request.data.email,
unsafe_cover_letter = request.data.cover_letter,
safe_cv_url = request.data.cv_url
]
(context django)i am getting this error while deploying on heroku
$ heroku run python3 manage.py migrate
django.db.utils.ProgrammingError: relation "auth_user" does not exist
when i migrate on my machine it works fine
using Flask, and on Heroku I keep getting this error: bash: gunicorn: command not found
but I do have gunicorn on my requirements.txt file, any ideas?
and i do not have a pipfile
i get H10 app crashed error
hi all, if anyone has a good flask api tutorial, can share it with me, thank you.๐
I'm using django with async views and aiohttp to make requests.
The site works fine on 1st request, but as I reload the page, the whole site breaks and raises RuntimeError: Event loop is Closed even though I didn't closed loop manually anywhere. Full Traceback: ```bash
Internal Server Error: /home/
Traceback (most recent call last):
File "C:\Users\Asus\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Asus\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Asus\AppData\Local\Programs\Python\Python38\lib\site-packages\asgiref\sync.py", line 222, in call
return call_result.result()
File "C:\Users\Asus\AppData\Local\Programs\Python\Python38\lib\concurrent\futures_base.py", line 432, in result
return self.__get_result()
File "C:\Users\Asus\AppData\Local\Programs\Python\Python38\lib\concurrent\futures_base.py", line 388, in __get_result
raise self._exception
File "C:\Users\Asus\AppData\Local\Programs\Python\Python38\lib\site-packages\asgiref\sync.py", line 287, in main_wrap
result = await self.awaitable(*args, **kwargs)
File "C:\Users\Asus\Documents\Projects\Aperture-Dashboard\ApertureDashboard\home\views.py", line 68, in index
async with cs.get(USER_ENDPOINT, headers=headers) as resp:
File "C:\Users\Asus\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client.py", line 1117, in aenter
self._resp = await self._coro
File "C:\Users\Asus\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client.py", line 429, in _request
handle = tm.start()
File "C:\Users\Asus\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\helpers.py", line 586, in start
return self._loop.call_at(when, self.call)
File "C:\Users\Asus\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 694, in call_at
self._check_closed()
File "C:\Users\Asus\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 508, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
This is how my views looks like: ```py
import ...
class AiohttpSession: # to make persistent session
def __init__(self):
self._session = None
async def get_session(self) -> aiohttp.ClientSession:
if not self._session:
self._session = aiohttp.ClientSession()
return self._session
aiohttp_session = AiohttpSession()
async def index(request):
cs = await aiohttp_session.get_session()
async with cs.get('some_url') as resp:
... # do stuff
I can't find any fix to it and instead found some bug in aiohttp https://github.com/aio-libs/aiohttp/issues/4324 Is there something I can do for it?
I can't post the thing here because it's too long so here is a link to stackiverflow
https://stackoverflow.com/questions/68129325/web-wocket-server-python-with-socket-module
im having trouble with creating web socket handshake with python sockets
because that's not the correct syntax for a list...
with selenium, is it possible to access elements with custom attributes?
such as:
<a href="" my_custom_attribute="my_custom_value">...</a>
is there a way to filter through these elements based off my_custom_attribute?
Hello. Does it make sense to create, edit and delete at the same time in an API? For example in a scheduling application. Just like what you see in the picture. The user can set the times he wants. Finally, after pressing the save button, create if there is no time interval. Update if there is and delete if not in the submission period.
is that hebrew
just asking lol
wassup I want to do a movies streaming website but I don't know where to begin, btw I just found that on another streaming website, let me show you
https://neko-sama.fr/css/nekosama-site.css?46b8876ebe46020f110b32756d973ca
Can I use that shit from this website? If yes, how ? Thanks in advance there's also those others links
https://neko-sama.fr/js/nekosama-libs.js?46b8876ebe46020f110b32756d973ca2
it's Farsi(Persian)
ah cool apologizes
Why do you apologize? You did not say anything bad. it was only a question.
I apologized for my wrong guess
You can migrate then push
Or add it to ur Procfile
hey guys, i have actually tried the django , and other frameworks, one is there.. um i think the name is cherrypy, but thats not what i really wanted................ i was looking for a technique for putting the python code in the html program, just like we put the js and css code into html
and also do you guys know what an arduino is? its basically a pcb through which you can program a hardware, programming lcd screen and other things, you must know it, so i wanted to check if there is a way to connect the arduino to python programs, arduino works on C language ......
Django: what do you folks use for a mutliple select field? The default UI/UX of the default one is terrible. I cannot for the life of me, extract the js/css from the admin for the multiple-select widget and you can't invoke it while not being logged in as superuser.
@ember adder how do you use a custom one though?
and a related question: is there a way to display a filter (search box) in a select box of a one-to-many field in the admin?
Yes, and it's builtin. Look into the filter_horizontal and filter_vertical options on your ModelAdmin class:
https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.filter_horizontal
@mild bridge I tried to use filter_horizontal, but got a message it's only for many-to-many fields?
how do I override though?
If there really are no builtin widgets that can help, then presumably you want to implement a custom one:
https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_overrides
I'd still have a once-over of the ModelAdmin docs though, there are plenty of useful builtins there that might be able to help
is there a list somewhere with all the builtin widgets?
cc: @ember adder on overriding frontend for field inputs, custom widgets are generally how it's done
so for something that allows filtering on the frontend, I would need JS. Do I just add a template with JS?
is there an easy/semi-standard way to integrate react here (in the admin as a custom widget) or something? since just rendering a small react component would be easiest for me
yep. Or at least that's how we've done it at work, there might be a more idiomatic way of doing things but we usually stick a <script> tag inside the template and tell the template_name classvar to point to it
I see. what exactly do you mean by point to it?
I mean just use the standard relative path from any TEMPLATE_DIR
Like if your template is in src/core/templates/plugins/multi-select.html you'd do template_name = "plugins/multi-select.html"
and the multi-select.html is just whatever? some html, some JS, some CSS? what's the API for widgets
I'd have a look through some of the builtin ones for reference:
https://github.com/django/django/tree/main/django/forms/templates/django/forms/widgets
Since widgets are basically just rendered inside forms, they can really just contain anything alongside any valid form input element. You'll need to make sure the type, name and value attrs match the ones in the widget instance passed to the template context, see input.html for reference
but how does django take a value from it. What if my widget is not an input
In the vast majority of cases you can just get away with overriding the template for one of these builtin widgets rather than defining your own, I just find it's more explicit to do the latter
@mild bridge let's say I want to use this as a custom widget: https://react-select.com/
I'm not really familiar with how custom widgets play with React, it's probably worth looking at some existing projects for a point of reference
I'm trying to find some
I'm sure react-select will render an input element to the DOM at some point, don't really see how else it would function as a form input
So (I assume) it'll just be a case of telling React to render your component in the context of your template override
yeah but what does django expect exactly? Do I give it the input an id/name attribute and it takes it from there? is it just an html form?
the docs for the admin are a bit sparse
Looking at how the default select widget renders things should give you a good point of reference, I'm trying to find an example of how the frontend guys do it at work
@iron obsidian as far as I can tell, it's just a case of setting name to your field name, and id to id_ + field name
Thanks. do you know why the id_ + field name is needed?
nope ๐ it might not even be needed, I'm sorta just going off some templates that were written for a custom widget recently
I don't really work on that side of things
๐ ok, thanks so much!
I'm thinking about rolling my own admin with react-admin . I don't know if playing with semi-arcane template stuff in django admin would take less time than just doing it myself
@mild bridge do you know if there's a custom channel/discord server for django?
AFAIK this is the closest thing to a Django channel in PyDis but there is a Django discord server too: https://discord.com/invite/FyqGdKEf
@mild bridge thanks. btw, unrelated, but how do you name a django project? this seems so random..
The project as a whole? It doesn't really matter much, naming your apps is what's actually important (i.e. your distinct django apps, not the webapp as a whole)
There's a pretty good chapter on Django app best practices in Two Scoops of Django 3.x, which I highly recommend: https://www.feldroy.com/products/two-scoops-of-django-3-x
so what do you call the project? just "project"? "config"? name of company?
please solve my problem: https://stackoverflow.com/questions/68182327/app-is-not-showing-up-in-django-3-0-admin. the question is on stack overflow.
I have put my app in the settings.py:
'jet',
'jet.dashboard',
'store.apps.StoreConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'd...
@mild bridge Thanks for the link. However this multiple select is the basic one with an awful UI/UX. Forgetting to press control on selecting, you can lose all your selection without knowing it and that's very bad. I'm trying to have something similar to the one in the admin, but I can only extend it for users that are logged in as admins.
hey
is this for webscraping too?
in requests library, I want to do a POST request. How do I know the name of the values etc so I can post them?
For example, I will do a dictionary {"name": "value"}
How do I know what the "name" is. Do I go to the website and do the post request manually, then check what is sent? How do I check what is sent?
Thanks in advance
I'm trying to run a Flask/SQLAlchemy application and getting Internal Server Error - details in #help-honey
I am using brython. I am trying to get user avatar from oauth2. I cant import discord. What to do?
quick question with flask, is there a way to get other body data when submitting a post request?
If your submitting a form, you can use request.form
that only gives me input tag things
I'm not that good at flask, but in pretty sure request.form returns a dict
In ur html
The tags you want to submit in the form need to have a name
Also make sure you are using correct URLs and methods
uhh... its fine to generate input tags with name dynamically right?
these are all input tags with some names
but request.form only gives me this
well you only submitted one input
the rest are disabled
i don't think disabled ones get submitted in the form
you can have them hidden
see this question
ouh! that's neato
yeah you can set the input to be hidden and set a value if you don't want the user messing with them
<input hidden='hidden' name='foo' value='bar'/>
noice, works
one last thing
i wanna send those coords as well
they change dynamically when the user drags the element
is there a way to send em
you should probably use javascript and reactively update hidden inputs
ah.. fair enough
then submit them with the form
so the only way to interact with flask and html is forms
flask is meant to be used as a backend service
you can also make a rest api with flask
and use javascript to interact with it
mehhh that's overkill.. smth with jinja is what i needed
but yeah, this is a clean way
yep
I am wanting to parse through this XML and change the CUSTID within the keywords but I don't want to make changes to the other keywords. I can't make changes to this file because I don't own it to do so.
<?xml version="1.0" encoding="UTF-8"?>
<example_root>
<keyword_defaults>
<keyword>
<name>REPORT_DIR_PATH</name>
<default_value>/example/path</default_value>
</keyword>
<keyword>
<name>CUST_PATH</name>
<default_value>/Example/cust/path</default_value>
</keyword>
<keyword>
<name>DefaultCustomerId</name>
<default_value>NEED TO CHANGE THIS(this is like a 6 Character code at most)</default_value>
</keyword>
<keyword>
<name>Cloud server</name>
<default_value>examplecloudserver.com</default_value>
</keyword>
<keyword>
<name>Example_TAG</name>
<default_value>ABC123</default_value>
</keyword>
</keyword_defaults>
Parse through it using python.
I know a little about ElementTree but I am not sure how I would pick out the specific keyword with the DefaultcustomerID txt that I need to change.
Hi Django Channels doesn't support JWT auth by default using workarounds we can send the token as a query parameter
But this exposes the token
How do I go about managing this?
This is for a group chat, a user can have only 1 group chat
So the address would be /group/<groupname>
is anyone here familiar with 000webhost? if so, is it possible to host a web app which displays the contents of a .txt file a user uploads using 000webhost and python?
according to their website, 000webhost deploys php apps
so ima have to learn php?
no
you can use another cloud provider
like aws, gcp, heroku, etc.
i suggest heroku cuz it is really easy to get started and it has a pretty decent free tier
replit.com provides cloud hosting and a dev environment
@paper briar
alright thanks a lot
i tried deploying a django app into heroku but after too many errors i just gave up
i've also tried to try aws but had to stop when it asked for my credit card lol
yeah thats kind of annoying about heroku
you need to know a bit before you can make stuff
all ur errors are probably coming from the fact that your procfile is missing or has bad commands
i think i got stuck at the procfile
https://replit.com has unlimited "repls" (your code) that can be deployed really easily
:oooooooooooooooooooooooooooooo
yeah its kind of a miracle
quite
i would count myself familiar
Hello
I am trying to modigy a certain model field after the user sends a post request in the API
class PostList(ModelViewSet):
permission_classes = [PostUserWritePermission]
serializer_class = PostSerializer
def get_object(self, queryset=None, **kwargs):
item = self.kwargs.get('pk')
return get_object_or_404(Post, slug=item)
def create(self, request, *args, **kwargs):
post_data = request.data
slug = post_data['title']
print('THIS IS SLUG', slug)
print(post_data)
new_post = Post.postobjects.create(post_data)
new_post.save()
serializer = PostSerializer(new_post)
return Response(serializer.data)
def get_queryset(self):
return Post.postobjects.all()
```
Not going good so far cuz I am getting this error create() takes 1 positional argument but 2 were given
and It is coming from this line new_post = Post.postobjects.create(post_data)
This is the Post Model ```py
class Post(models.Model):
class PostObjects(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='published')
options = (('draft', 'Draft'), ('published', 'Published'))
category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1)
title = models.CharField(max_length=250)
excerpt = models.TextField(null=True)
content = models.TextField()
slug = models.SlugField(max_length=250, unique_for_date='published')
published = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_post')
status = models.CharField(max_length=10, default='published', choices=options)
objects = models.Manager
postobjects = PostObjects()
class Meta:
ordering = ('-published',)
def __str__(self):
return self.title```
And this is the post serializer ```py
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('id', 'title', 'slug', 'author', 'excerpt', 'content', 'status', 'published')
I want to add django-wiki and django-tagulous to my own project
https://django-wiki.readthedocs.io/en/latest/installation.html
I've read the docs and other sources and I gather I need to create an app in my project and override the django-wiki pages.
But the docs don't explictly list what to override (views, urls).
I splunked the module's code, but I don't recognize the patterns.
What's the first step to integrate django-wiki (which is really a whole django website by itself--i know because I've installed and tested the wiki by itself).
_"You can override default django-wiki wiki.sites.site urls/views site implementation with your own: override by setting the default_site attribute of a custom AppConfig to the dotted import path of either a WikiSite subclass or a callable that returns a site instance." _
https://django-wiki.readthedocs.io/en/latest/customization.html#site
This just doesn't make any sense to me...
woah... django jobs are growing quite a bit (or it might be the time of year?)
I remember at the start of this year, there were about ~550 in my country. Now it's 700, pretty good growth
also - I have a webscraping module of my webapp. If I want to have it as a seperate service, i'll need to allow it to have its own API right. So, would I setup a new django project and containerize that?
hey guys ik this is a python server but does anybody here have bootstrap knowledge?
It's okay to discuss Bootstrap here. What's your question?
for some reason my nav bar is working fine
however the dropdown button just isnt working
@proper hinge
Which version of Bootstrap?
Can you produce a minimal example of the problem?
i.e., take away as much stuff as possible, but leave enough that the issue can still be reproduced
Could I have an explanation/solution on why the soup object does not have the h3 element?
import requests
from bs4 import BeautifulSoup
response = requests.get(url="https://www.empireonline.com/
Can anyone please please please try answering this thread
does it have to do with js or something
thanks!
are there any hosting providers that offer free hosting such as heroku that one would recommend to deploy a django project on?
The Coding Den discord
?tag largehosting
Free:
- Openshift: https://www.openshift.com/
2gb of memory, automatically expires after 60 days, but you can resubscribe as often as you'd like. - Heroku: https://heroku.com/
No CLI or SSH, no file access, might make your app sleep if you reach monthly uptime limit. - AWS (Free tier) https://aws.amazon.com/free/
Free tier containers from Amazon, expires in 12 months - Google Cloud Platform (Free tier) https://cloud.google.com/
Free tier google cloud servers
Paid:
- Azure https://azure.microsoft.com/en-us/
Starting at $1.69/month for their B1LS virtual machines, 0.5GB of ram and 4GiB of SSD storage. - OVH: https://www.ovh.com/us/vps/
Full VPS starting at $3.49USD/month, choice of OS, high reliability. - Digital Ocean: https://m.do.co/
Starting at $5/month (USD), you can have your own server with 20GB SSD Disk, and 512MB Memory. Use https://bithost.io/ if you want to pay with cryptocurrencies. - Linode: https://www.linode.com/
Starting at $5/month (USD), you can have a server with 20GB SSD Disk, and 1GB memory - Vultr: https://www.vultr.com/
Starting at $2.5/month (USD), you can have a server with 20GB SSD Disk, and 512MB Memory - Amazon(AWS) Lightsail: https://amazonlightsail.com/
Starting at $5/month (USD) (first month free), you can have your own server with 20GB SSD Disk, and 512MB Memory. - VIRMACH: http://virmach.com/
Full Windows and Linux Desktop VPS starting at $7USD/month and $10USD/month respectively. - Sloppy: https://sloppy.io/
Starting at 5$/month (USD) You can have 500MB Memory, 1TB Transfer per month and 16GB of storage. Extra
storage and ram can be bought. - Galaxygate https://www.galaxygate.net/
Starting at 3$/month (USD), get 15GB of storage, 1GB of ram, and unmetered bandwidth. - Hetzner https://www.hetzner.com/cloud
Starting at 2.49โฌ/month (EUR) for 20GB of storage, 2GB of ram and 20TB of traffic.
all free tier hosting a bit, not reliable.
be ready in any case for your work being deleted at any moment
if you can afford I would recommend using Hetzner for example, they provide quite cheap offers for testing/development
I have no reason to believe free tiers of Google, AWS, and Oracle (you didn't mention that one) would be unreliable. They just give you fewer resources to work with.
It's not like the classic cPanel free hosts that are stuck in 2010 or whatever.
shrugs.
That's just rumours I saw somewhere. not having first experience with free tiers
I always choose just cheapest VPSes for testing/development
Alright I want you guys to hear me out because I am genuinely confused. I did inspect element on my schools website and found a bunch of links to some questionable sites.
good day guys ๐
-
is there some recommendation course for web develop(django) for Django beginners?
I'm familiar with JS, TS, Java, Node, Rails. -
is there some good reference open-source for developing insight?
of course, all open-source must have reason and something for learn.
But I'm looking for some reference for develop library system for internal team
thanks in advance!
You could check out Flask, if you like. It's smaller and easier to use
https://github.com/BrainStormYourWayIn/sierra
You could use this as the templating engine for Flask, over jinja. You can do the whole thing in Python without touching another thing
The syntax is really small and easy too
For my personal project I would love to try that.
But this time is for enterprise commercial system.
I planning to move python base team ๐
And they use Django
Oh that sounds nice
This is just a templating engine, so you could use this with anything, really - Flask or Django
The fact that this is Python-only and the syntax is really short AND you can use this with even advanced stuff defo makes this my go-to
How do I hide my sensitive data like smtp configurations and secret key in django projects if I want to host my website online?
you store your keys in your userdata
or create one every 5 seconds
can you explain what is userdata?
Create a shared credentials file, which is used in the SDK examples for .NET, Java, PHP, Python, and Ruby.
Planning to move base team in the sense?
From JS, TS base team to Python + Django base team
That must be a big shift
ok thanks
MYP Personal Project?
Hey, I have been working with a website with Django as backend (like 4-5 s)
I am experiencing a severe latency for the application to fetch data from database and render
is there a way to do client sided rendering by using ajax
i mean something similar to what react does with array.map()
can anyone suggest me quick way to learn flask?
I would recommend some tutorials from tech with tim or miguel grinberg
thank you for your suggestion
help me pls
Look at the documentation. Seriously
You can start off with this
https://flask.palletsprojects.com/en/2.0.x/quickstart/
!d flask
This part of the documentation covers all the interfaces of Flask. For parts where Flask depends on external libraries, we document the most important right here and provide links to the canonical documentation.
create() got multiple values for keyword argument 'slug' is the Error I get from this code line return Post.objects.create(**validated_data.data, slug=title)
This is the full view```py
class PostList(ModelViewSet):
permission_classes = [PostUserWritePermission]
serializer_class = PostSerializer
def get_object(self, queryset=None, **kwargs):
item = self.kwargs.get('pk')
return get_object_or_404(Post, slug=item)
def get_queryset(self):
return Post.objects.all()
def create(self, validated_data):
print(validated_data.data)
title = validated_data.data["title"]
print(title)
# Once you are done, create the instance with the validated data
return Post.objects.create(**validated_data.data, slug=title)```
When the user sends a post request to create a post, I want to automatically fill in the slug field for them with the current value the title holds.
but also make modifications to that title before doing so like: .lower(), .split(' '), .join('-')
what does this mean message=form.cleaned_data.get('message') , does it mean that username's cant be same , cez i cant make same username , and what if i remove this line
@dusk portal it means that message becomes the value from your message input on your form after it passes through your form validation.
value of the input field on your form called "message"
ok so django forms have automatic 3 input , username , password and reenter password why cant i use
password
can i?
and what this means
form.cleaned_data, why this
what is this
what this do
ohh
how can i make my email also unique same as username cant be same
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
first_name=forms.CharField
last_name=forms.CharField
email=forms.EmailField()
class Meta():
model=User
fields=['first_name','last_name','email','username','password1','password2']```
Check if the email exists, then return a message if so.
You could do a quick lookup to see if the user email exists already before the function continues.
but how ,as in username it is automatically given by django forms
How would you look anything up? You can query the DB.
yes in my admin page users are getting registered
Do you know how to query the database to get a user, for example?
Keep it up, you'll get there.
Better you understand what you need to do, and then learn how to do it following the tutorials.
so figure out how to search the DB for a specific variable.
Such as:
user = User.objects.filter(email=email_address)
oh
If the user exists, return a message and don't create the user.
That's ok, keep it up.
Hi, are there certain html tags that are completely safe , that is I can let users use those tags in their posts? I am making a django site where users can use (custom) bold, italicize and image tags which are not escaped. Is this safe?
Not really. From what I've read, unless you know the data is absolutely 100% safe, like your own DB or function return messaging, you shouldn't use it without some kind of custom markdown implementation.
But there are libraries out there to take care of that.
where can I find them?
Is TinyMCE safe? I used it and it didn't even close unclosed tags.
It might not be, I don't use those libraries. You'll have to check on that.
in 2010 year we used bbcode for that
apperently it is still in use
Ah thanks I will check it out
I want to have my webscraper as a microservice to my django app. For them to communicate, I need it to have an API. So would I start a brand new django project for each microservice?
depends
normally โmicroserviceโ implies โcan be deployed independentlyโ
so if you mean that, yes
are there any other choices?
and i want each of the h1 tags to have a class of bold
is there a way to apply classes to the element automatically
django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Why's this happening when in manage.py the correct env variable is being set?
Its fine)))
hey guys
django is'nt throwing exceptions for unqiue together constraint when i save it and it instead saves it. But it works in the admin page.
@gritty cloud Is it not just applied like CSS throughout your html? Like just to the class attribute?
Can I get any link about beginner's tutorial?
uh no it only renders the h1, but i want to also apply the bold class to all the markdown rendered h1
The docs seem to show how to extend the default values that are applied:
https://django-markdownify.readthedocs.io/en/latest/settings.html
To what framework/library/language?
Hello. Iโm trying to display images from a folder in an HTML webpage. How do you form a folder path with a variable file name? Could anyone help with this?
Iโm using pycharm flask
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'accommodations',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'db',
'PORT': 5432,
},
Database settings ^
The Host refers to my postgres container. But what if I want to run my webapp locally and use localhost?
how do I apply CRUD functionality in django databases?
If your app creates, reads, updates and deletes database entries, you have CRUD functionality
so make seperate views which handle that.
Ok
f-strings?
my_file = "cat.jpg"
path = f"path/to/images/{my_file}"
# print(path) -> path/to/images/cat.jpg
Ummโฆ no Iโm not trying to print the path. I want to display images that are stored in the static folder.
But the name of the file is a variable
yes, so you can form variable paths like that, which you can then pass to your html template
How do I create a redirect link with django?
Okay Iโll try this n see
ERROR: Could not find a version that satisfies the requirement psycopg2-binary==2.9.1 (from versions: 2.7.4, 2.7.5, 2.7.6, 2.7.6.1, 2.7.7, 2.8, 2.8.1, 2.8.2, 2.8.3, 2.8.4, 2.8.5, 2.8.6, 2.9, 2.9.1)
ERROR: No matching distribution found for psycopg2-binary==2.9.1
it literally lists 2.9.1 as an available version
Okay so this didnโt work
Itโs still returning the string name and not the picture
that will return the path to the file based off the variable, show some extra code
@unreal heath
In my Django project is it better to not use the Django ORM?
@graceful flax What's the reason you ask?
Made a whole backend for an app, now came across articles saying the ORM is bad
Few articles mentioning ideally no ORM is best
hi anyone FLASK expert here? I have page A with form search, form points with payload in URL to page B so page B for example has ...?query=Cats. Ok cool, I have some dummy data in my main_run.py like:
dummy_data = [
{
'name': 'Dog',
'age': 2
},
{
'name': 'Cat',
'age': 1
}
]
and I want to show in page B data of query from link, if it is a Cat, then it will display something like {{ data[0].name }}. I tired in my page B do smth like:
@app.route('/pageB?q=<LINK_DATA>')
def page_b(LINK_DATA):
if LINK_DATA in dummy_data:
LINK_DATA = LINK_DATA
else:
LINK_DATA = 'Dog' # just for test
return render_form('page_b.html', data=LINK_DATA)
And I get an error like I forgot provide data for LINK_DATA
Why do they say it's bad?
generally, ORMs are good
people poo poo ORMs because it takes away the need for learning the raw SQL which often can lead people to writing less than good queries just because they dont necessarily understand whats going on behind the hood.
in terms of management, ORMs are great, combined with automatic migrations it makes maintaining the code base considerably easier
but to use them well you do still want to have some SQL / applicable knowledge in the DB design first so you're able to better visualise how the system is going to produce the queries and how that's going to affect performance and efficiency etc...
Yea they make my life easier for sure.
Hi, i would like to do an event like discordy but with a website. So i. e. when a value or something changed on a website then it will trigger my pthon code. I was thinking to use a while True loop so it checks if the value is the same as the previous request, but i think that's a bad way to do that. Do you have any ideas?
cant do parameterise like that. for url queries like that you need to use the request global and do request.args.get('key here, in this case q')
yes thank you very much for explanation, docs here as well: https://flask.palletsprojects.com/en/2.0.x/api/#flask.Request.args
This is one point
It seems like a common sense question and I think the answer is yes, but I still wanted to ask.
If the internet speed is slow, then does it mean GET and PUT request would also be slow?
Those involve sending data over the internet. Therefore, they are affected by the speed of the connection. So the answer is yes.
However, when discussing slow internet, it usually means low bandwidth. If the requests don't send a lot of data (e.g. only a kilobyte), then you wouldn't notice.
ok that makes sense so something like GET and PUT wont get effected if it's sending and receiving couple of kilobytes of data, when the internet itself has couple of mb in download and upload.
Thanks!!
hello everyone
Hi, i have a little quiestion about django, and is what is the purpose of use Django Rest Framework if i can use "return JsonResponse" and use is like an API
How can I add a button that when I click it, it will print ("Hi") in console (Django)
i am working on a projet in django , all is working fine , but after adding modals with ajax i have a message like this "broken pipe" ? can anyone explain me , i really don't know how to fix it please!
Are you using fetch?
can i see your Ajax call?
ok
it happens when i'm trying to add a new product
it's opening modal pop up forms
Common restapis need later things more than jsonresponse, drf covers all needs in extra libraries... starting from making it very DRY with its internal two way json serializers
html
<form action="" method="post">
{% csrf_token %}
<button type="submit" name='mybtn2'>Download results in Excel</button>
</form>
all that I want this to do is print ('hello') in console.
if request.method == "GET":
print("hi")
how can I go about doing this?
They offer things like throttling limit there for example too (to limit amount of requests from same ip against abuse)
you are using POST here in your html form
even if its post tho, it doesn't really work
it refreshes the page
and it doesn't say "hi"
do you want just a button that print hi ?
I don't want to redirect to a new page tho
and css to have like button
eh
why when I refresh the page, does it run that function?
and like how can I stop that
bro did you have any suggestion ?
Anyone know how to change a flask.py from localhost to public?
On linux(ubuntu) with no monitor?
step one: installing gunicorn in order to run your server in not development mod
gunicorn -b localhost:8000 -w 4 microblog:app
technically you could point here 0.0.0.0:8000 adress...
but better as next step installing Nginx
as it is shown in the guide
and making redirect from nginx to gunicorn
oh wow, yes this looks good let me see if I can get it up
Please suggest some best free hosting for flask
ping on reply
hello
ineedhelp
When I don't place any image the page crashes, and I have the arguments set to True so that it accepts that the page doesn't need an image
If I put an image on it, it obviously works
Hi, I am facing this warning in ariadne, please help me.
ASGI 'lifespan' protocol appears unsupported
should i put routing inside my frontend (react) or my backend (django)?
This part of the documentation covers all the interfaces of Flask. For parts where Flask depends on external libraries, we document the most important right here and provide links to the canonical documentation.
Either works
i see
Use whatever works best with what you're doing
but is there any advantages tochoose one over another?
Backend's always better, if you're dealing with a big project
Not really
yea going for a big project
It's very dependent on 1, your preferences, 2, exactly what your project is
interesting
Like, if your backend is just a REST API that's deployed on a different subdomain, you wouldn't do routing there
icic
Hey guys had a questions about Swagger UI the api docs one, if anyone can help let me know
swagger is just showing wrong rounded int values on my side so wanted to know if there are any fixes for that
I am trying to make a social media site.I have completed its backend and strugling in creating its frontend
Please
help
thats kind of a broad issue
if you on django, you can choose a framework or plain html and js
anyone good with flask? i'm trying to redirect the user on successful form submission using py return (render_template(url_for('cafes'))), but it doesn't wanna work
you would then need to incorporate an API for passing data to and from
the front and backend
you don't need url_for
only the html file's name
make sure that that html file is in a directory called templates in the same working directory as your main.py
the page takes an opened csv as an additional argument, and to prevent myself from duplicating code i wanted to call the function instead of repeating myself
uh wdym argument?
@app.route('/cafes')
def cafes():
with open('cafe-data.csv', newline='', encoding="utf8") as csv_file:
csv_data = csv.reader(csv_file, delimiter=',')
list_of_rows = []
for row in csv_data:
list_of_rows.append(row)
return render_template('cafes.html', cafes=list_of_rows)```
o ok
well this itself should be good
just make sure your files look liek this
main.py
templates
|___ cafes.html
๐ i have the templates/static folder
nice
throws this py jinja2.exceptions.TemplateNotFound: /cafes
is this happening with other routes as well?
no
first could you give me the entire traceback?
so we can determine whether its your fault or a bug
jinja2.exceptions.TemplateNotFound
jinja2.exceptions.TemplateNotFound: /cafes
Traceback (most recent call last)
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\venv\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\venv\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\venv\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\venv\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\venv\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\venv\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\venv\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\venv\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\venv\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\venv\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\main.py", line 46, in add_cafe
return (render_template(url_for('cafes')))
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\venv\Lib\site-packages\flask\templating.py", line 138, in render_template
ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\venv\Lib\site-packages\jinja2\environment.py", line 930, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\venv\Lib\site-packages\jinja2\environment.py", line 883, in get_template
return self._load_template(name, self.make_globals(globals))
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\venv\Lib\site-packages\jinja2\environment.py", line 857, in _load_template
template = self.loader.load(self, name, globals)
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\venv\Lib\site-packages\jinja2\loaders.py", line 115, in load
source, filename, uptodate = self.get_source(environment, name)
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\venv\Lib\site-packages\flask\templating.py", line 60, in get_source
return self._get_source_fast(environment, template)
File "C:\Users\Conan\PycharmProjects\coffeeAndWifi\venv\Lib\site-packages\flask\templating.py", line 89, in _get_source_fast
raise TemplateNotFound(template)```
try using just render_template('cafes.html')
i get cafes is undefined
it looks like your url_for is tripping it up
cause i'm not passing the csv data
i mean i can just pass the csv data, but didn't want to repeat myself ๐ i don't know if that's good practice or not lol
what do you reckon?
idk lol im pretty trash at flask
re. the repeating thing :p
o
i could just throw it in a function
i would do that
np
maybe open a help channel for your template not found thing
ul find much more big brain people than me
it's ok =] you've been very helpful, thank you!
@obtuse whale use:
if form_on_submit(): return redirect(url_for('SOMEWHERE'))
html and css by john duckeet
is it worth buying , can u tell a book which follows a project based approach for html and css for beginners
# List of similar posts
post_tags_ids = post.tags.values_list('id', flat=True)
similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:4]
source - django by example pg-64
will not this get posts which share atleast 1 tag with post and has the most tags (not common tags)?
i tried with their repo and its recommending posts with most no. of common tags but how?
any ideas?
i need help
this is my final year project im working on ..but im getting an error not allowed to load local files on chrome any solutions?
:(
Which library do you recommend using to develop an app that does web scrapping to web aspx including login? BeautifulSoup is good for that?
@opaque rivet but selenium not need a browser driver and open browser? Sorry I new about that.
Is there any API doc for Selenium 4?
i have these h1 and p tag in a container h1 aligns in center when only h1 is present as soon as i add p tag it becomes like this
selenium needs browser driver (chrome, firefox, or whatever you will put in)
but it can run in console mode (headless mode)
@inland oak I will try dev an android app with kivy to interact with a aspx web that I dont have control, is good idea use selenium for that? What think abaut activeSoup?
Not familiar enough with your stack.
In general selenium should be avoided, unless you need loading javascript of your target.
htnl/css stuff can be handled with more lightweight solutions
And when site is intensive in javascript, better try finding their APIs first
Yes, I need load JavaScript, and this specific website dont have a public api...
Just ask your question
Ok
Someone will help if they can
Do you have the ep?
Huh?
What is the ep
:thinking_dinosaur_emoji:
is web gui harder to develop for my app then normal gui??(ive never made any python gui's b4)
I would say web gui is easier to code, but requires more skills to learn
woud u recomend any tutorials?
Head first, css book is nice place to start.
Tbh, perhaps desktop gui is actually easier to code may be
i allredy know basics of css and html i just need somethink for python, shoud i go flask or somethink else
I mean... simple desktop gui... can be requiring just several code lines
Flask is great to start with
Django is really nice, but it has more moving parts, so it may be harder to start off with
web gui is imo cooler but idk waht way i shoud go
Shrugs. Web gui solves a lot of problems... like no need to have difficult client side app updates. Which can be quite painful in desktop
Web is definitely easier for people to access as well
Yeah, removing installation issues too
95% of users have access to modernly updated browsers
ok im going webgui
Just 5% keep using super oudated internet explorer or veeeeery early firefox/chrome
Recently caught user using forefox 4 .. while current one is 89
y woud some1 put themselves thru this
Web gui can be made friendly to account even them
also can you have local web gui just on your masine and not for your network, right?(just makinng sure)
Yeah
For development of course
It can be made accessable by your localhost only
yeh i want my app to only be on localhost all the time cus its a otp client
Wait a second, you are actually asking could be it for user in user machine only
Not for development purposes?
yes
It can be too... But architecture of security for that is a separate topic :)
And backend and front-end protected with different ways
why do you need to protect it if its only for your machine
Because it is in browser.
And browser is accessed by many different javascript applications without really... restrictions
oh heavent thaught of that
Hey so
from flask import Flask, request, url_for,render_template
app = Flask(__name__)
@app.route('/home')
@app.route('/')
def home_page():
return render_template('home.html')
@app.route("/user/<name>/<surname>", methods = ['POST'])
def show_info():
name = request.form.get('name')
surname = request.form.get('surname')
return render_template("result.html", the_name = name, the_surname = surname)
if __name__== '__main__':
app.run(debug=True)
``` This is a normal flask code
{% extends 'layout.html' %}
{% block content %}
<form class="main-input" action="{{ url_for('show_info')}}" method="post">
<label class="label" for="name">Enter your name:</label>
<input class="firstname" type="text" id="name" name="name">
<label class="label" for="surname">Enter your name:</label>
<input class="surname" type="text" id="surname" name="surname">
<button class = 'click-button' type="submit">Click</button>
{% endblock %}
{% extends 'layout.html' %}
{% block content %}
<h1>Hello {{ the_name }}, whos last name is {{ the_surname }}.</h1>
{% endblock %}
``` and these are the htmls
so basically what I am trying to do is to pass name and surname in the url
when the user puts them in the field forms
but instead I get errors and cant find a way to fix it
like, how can I specify those values? I tried googling
You specified show_info's url with /user/<name>/<surname>, so when you use url_for with show_info, you need to pass in name and surname as kwargs.
I suspect that there's no reason for you to include name and surname for the show_info url, since you're getting those from the form.
Hey guys I tried to create a database using sqlalchemy
But the class isn't providing any of the methods or functions while calling it.
Even after I imported that class again
What do you mean by "methods or functions while calling it"?
The method of that imported class
Like while importing pandas as pd
We can use pd. read_csv so that's the method or function of that pandas class
any django dev rn on?
Is it possible to store data in cache per user session?
Like I fetched an API with a lot of data and I need to access it everywhere until user browse...
caching databases allow storing data by key
so... just store user session key in it ๐ or something like that
just make sure you output valid, not outdated data
hey bro can u help @inland oak
Yeah that could be done... Thanks :)
class Profile(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
image=models.ImageField(default='notactive.jpg',upload_to='profile_pics')``` why we r adding upload_to and what's the difference between ForeignKey and OneToOneField

plz
different amount of objects to objects...
for example you have Profile
every User instance should be having its own Profile instance and only one
it makes it perfect (one to one) relationship
but for example you created Message, there can be a lot of messages to one user
that would be already perfect for Foreign key relationship (one to many)
Foreign key is used to attach a lot of objects to one object
OneToOneField basically extends the same model
@inland oak
if request.method=='POST':
form=UserCreationForm(request.POST)
if form.is_valid():
form.save()
message=form.cleaned_get('message)
So tell me why we r using this last time after its saving info to the db
I encounter this code using Flask in Python. This is the Jinja used html file. I wonder if the word "content" in {% block content %} is a reserved word or any other coder determined word.
{% extends "base.html" %}
{% block content %}
<div class="container">
<h1 class="title">Welcome, Name!</h1>
<a href={{ url_for('download') }}>Download Your File</a>
</div>
{% endblock %}
https://jinja.palletsprojects.com/en/3.0.x/templates/#base-template
I think you can define them on your own. At least that what I understood from the link above
depends on which blocks your have in base.html
i'm getting a werkzeug invalid key error and can't find out why
@app.route("/add", methods=['POST', 'GET'])
def add():
if request.method == 'POST':
new_entry = {
"book_name": request.form["book_name"],
"book_author": request.form["book_author"],
"rating": request.form["rating"]
}```
and
```html
<form action="{{ url_for('add') }}" method="POST">
<label>Book Name</label>
<input type="text" name="book_name">
<label>Book Author</label>
<input type="text" name="book_author">
<label>Rating</label>
<input type="text" name="rating">
<button type="submit">Add Book</button>
</form>
i mean, as far as i can see it seems fine, and i've tried changing the tag names but no dice
How do I use django with aiohttp or some other async libs? Idk just using them normally in a view works fine just when I load the page but causes errors like RuntimeError whenever I reload...
I need to use discord.ext.ipc in particular
[Q] simple flask variable:
So I have in main app this:
@app.route('/')
def index():
my_name = 'abc.jpg'
return render_template('some.html', my_name=my_name)
and I want that vairable my_name in my some.html:
<!dcotype etc...>
...
<div style="background-image: url('{{ url_for('static', filename='img/{{ my_name}}') }}'); ">
...
Notice how {{my_name}} doesnt work in link in .html file; but works if I put it in <h1> tags for example. Why. See how it destorys my var: ???
I get error GET /static/img/%7B%7Bmy_name%7D%7D HTTP/1.1" 404
guys im using django as my backend and using vue js as my frontend so i was trying to get data from database and this happened
i have no idea
oh wait it was my mistake
solved
I already went through that and now using async views only... But I get into problem related to loops and asyncio, like how to use common ClientSession across the whole site or app (persistent ClientSessions) and stuff like that... Also tried to find any docs or resources but can't find anything 
can anyone please tell me how i can connect my flask app with react frontend ?
ok
but i have already made some of the frontend part on templates and that is using the data from flask, what how do i use that on react?
found solution, just do:
url('{{ url_for('static', filename='img/'+ my_name) }}');
React suggets you will run javascript requests to your Flask API in order to get data.
Flask should give data in json format
i see
Hi, is there any method to invalidate sessions in all devices using jwt (Django)?
For example, when changing passwords
I just store in jwt hashed passwords ๐
when they aren't matching, I deny jwt decoding
a bit silly approach tbh
but hey, it works
Haha ok, I'll keep it in mind, thanks
I mean... jwt is... basically
dictionary + time variables
verified with signature that they were not tampered with
they were not changed
when you decode JWT
you verify that the data inside was not changed
so... you can keep safely for example something like
{
"User Level Permission": "10",
"IsUserAuthorizedToUseThingX": "True"
}
storing hashed password is essentially the same
How do I use persistent ClientSession with django? I need to use aiohttp and some async libs like discord.ext.ipc but I can't figure out how to use them...
Yes I'm using async views but directly defining all the libs stuff in views.py causes errors like RuntimeError and such...
I've been finding any guide or reference from past week but unable to find one, can't find proper docs in django official too... (Note I know how to create basic async views but that's not the issue with me) Thanks :)
i know its not community standard i just haven't changed it yet, going to do that here soon
anyone's up
Most likely
Do you have a question or are you just taking a poll?
LXD
any ideas on why it's not working
i tried switching the position of URLs and it still didn't work
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
image=models.ImageField(default='notactive.jpg',upload_to='profile_pics')
def __str__(self):
return f"{self.user} Profile"```
so simply i have created a profile and in that added one to one relation to indentify who;s adding img
so after selecting img i want to render it on my html
so im doing that
and adding that static too
idk why not working
hello everyone! i want to make a web app and add new features like sending verification to the user's email when sign up. But i am not sure which took i should use?
to be more specific is sending an code and the user need to enter the code in the website
if you're using django there are a premade views and urls you can use for various things like password verification , password reset. You can customize these to make to your liking to add new features.
https://docs.djangoproject.com/en/3.2/topics/auth/default/#module-django.contrib.auth.views
I'm sorry for asking a potentially stupid question:
Am I supposed to dig through documentation/source code to know what parameters go into each view function? Or is there a better way? I'm really new to Django
the offcial django docs are quite human readable, so yes
(I'm still wondering about hit counter)
How should I go about my view/hit counter?
- ALL views (including refreshed)
- Unique views (by IP or Cookie, per day)
In django, should I write my validator function for a textfield inside models.py, or should i make a separate file somewhere else?
I prefer to create seperate form.py
it can be done either way
Thank you so much!!
soo I made a url shortener in 32 lines of Flask :)
from secrets import token_urlsafe
from flask import Flask, redirect, request, render_template_string, flash
app = Flask(__name__)
app.secret_key = "Flask Good. Django Bad."
@app.route("/", methods=["GET", "POST"])
def index(args=None) -> str:
if request.method == "POST":
long_url = request.form["long_url"]
short_url = token_urlsafe(4)
app.add_url_rule(f"/{short_url}", view_func=lambda: redirect(long_url))
flash(f"Your short URL is: <a href='{request.url+short_url}'></a>")
return redirect("/")
return render_template_string(
"""
<title>Flask URL Shortener</title>
<style>a::after{content:attr(href);}</style>
<form action="/" method="post">
<input type="url" name="long_url">
<button type="submit">Add URL</button>
{{ get_flashed_messages()[0]|safe }}
</form>
"""
)
if __name__ == "__main__":
app.run("0.0.0.0", 8000, debug=False)
app.secret_key = "Flask Good. Django Bad."

hey anyone's up!!!
im making a blog app by Corey Schafer's video
and i have made an model for image and set all the path and it's working perfectly fine but idk why it's not showing any image
idk why
plz help
what framework are you using?
Django
i want to share screen

or screen shot's
Sorry I don't use it obviously. I am a flask guy 
ohh
u learned flask from where
i have learned it from own , it's ezz and good flask is good
flask docs are worst bruh!!!
The official docs are good!!
umm
why are you saying this?
read this yesterday. Its the worst docs I have ever read
or I am not comfortable with the framework
if u r saying this then i will surely try django docs
I think my experience has to do more with the framework
it doesn't do things the 'pythonic' way
it's like you are using a different language
in the other hand in flask you can make your app in seconds and just hit flask run or python app.py and it will just run
in django you have to make commands over and over and over to just get things to work
flask-admin bluh bluh bluh. There's a app and a project. 7+ .py files created with the project
Your app should scale at size and files as you scale not the other way around

can someone explain why the first one works and the second one doesnt? ```py
@app.route("/edit", methods=['POST', 'GET'])
def edit():
if request.method == "POST":
book_id = request.form["id"]
book_to_update = Book.query.get(book_id)
book_to_update.rating = request.form["edit_rating"]
db.session.commit()
return redirect(url_for('home'))
book_id = request.args.get('id')
book_to_update = Book.query.get(book_id)
return render_template("edit.html", book=book_to_update)
@app.route("/edit", methods=['POST', 'GET'])
def edit():
book_id = request.form["id"]
book_to_update = Book.query.get(book_id)
if request.method == "POST":
book_to_update.rating = request.form["edit_rating"]
db.session.commit()
return redirect(url_for('home'))
return render_template("edit.html", book=book_to_update)```
because you shadow your function names
you can only have one function with a given name
two functions in the same space with the same name is called shadowing and means that only the last function will be the function python uses / registers
you are requesting the "id" form input even if the request method is "GET". Moving the first 2 lines inside the if block should fix it
Flask doesn't allow shadowing
isn't flask just python?
Im not saying it does, Im saying thats why its not working
you can only have one function with a given name
okay then my bad
ok ๐ thanks for the heads up
kinda nitpicky but
I donโt think shadowing is the right term here?
itโs more reassignment right
shadowing is about scopes
like the first function will never be accessible again so itโs not shadowed, just gone
app.secret_key = "Flask Good. Django Bad."
I guess? But then you use the term shadowing when say someone does all = foo and it shadows the all() function, in the same sense it's the same thing?
I wouldnโt call that shadowing
if it was in global scope
this would be shadowing
a = 1
def f(a): # this shadows a from outer scope
pass
with sphinx is it possible to link a specific element from the index page?
So i have this img redirect to /accounts/startlistening/{{i.song_id}}
The url is here
here's the views,py
but for some reasons the url changes but it remains at the same webpage
I need to redirect to a music player, which it doesn't
Would really appreciate some help
should be possible, not sure how ๐
well, it provides auto generated menu at least for all header levels
you can use subheaders inside one page
i'm trying to run my flask application in a thread, but it doesn't seem to be working
the program just ends abruptly
and the site doesn't work
from website import make_app
from json import load
from threading import Thread
try:
with open("config.json") as file:
config = load(file)
except FileNotFoundError:
raise FileNotFoundError("""No config file detected! Please make a file called config.json with the following structure:
{
"serverAddr": [string],
"dev": [bool]
}""")
if __name__ == "__main__":
app = make_app(server=config["serverAddr"])
Thread(target=app.run, daemon=True, kwargs={"debug": config["dev"]}).start()
this is the code for the file im running
if i run the program it just ends
as i said
do you know what a daemon is and what it does?
doesn't it mean the thread ends when the program ends
it runs your program as a background progress
so i should make it daemon=False?
Yeah. Flask uses GET by default
can someone help me on why my css isnt updating it worked to put it there in the first place but I changed the background and it didnt change
any fixes or if you need code I can give that too
your browser is probably caching the file or your not saving your file
so I have a problem with sphinx, my toctree keeps on adding every header it can find
.. toctree::
:titlesonly:
:caption: Command Categories
moderation/index
image/index
Code ^
The warning that was raised, which I cannot understand
WARNING: toctree contains reference to nonexisting document 'commands/ :titlesonly:'
WARNING: toctree contains reference to nonexisting document 'commands/ :caption: Command Categories'
Hi, I'am doing an app with DRF, but I'am stuck on one thing.
I created API that can return JSON from model, with filtering and sorting...
Now I wanted to handle POST request, that will update DB records from static hardcoded url, which returns JSON as well.
serialiser.is_valid() returns True. But then, as I want to .save() I got this. "django.db.utils.IntegrityError: UNIQUE constraint failed: api_book.id"
Anyone could help on it? I got confused...
Maybe itโs caching it
Bc itโs on repl it so you donโt have to save
What is persistent storage on Firefox?
alr np
How do I include a module in webpack if I don't use it in any of my own JS modules?
The module in question is from npm - it's just something from the front end that works without me needing to interact with it in any way with JS
I probably could just import it anyway so webpack picks it up, but that seems like a hack considering I don't actually need to use it directly.
im trying to compress my image before i upload it to my table django, so far i have
def save(self, *args, **kwargs):
instance = super(Profile, self).save(*args, **kwargs)
img = Image.open(instance.image_file.path)
img.save(instance.image_file.path, quality=20, optimize=True)
return instance
but it returns a error 'NoneType' object has no attribute 'image_file'
my image field is ```python
image_file = models.ImageField(default=None, null=True, validators=[
FileExtensionValidator(allowed_extensions=['png', 'jpg', 'jpeg'])])
css and html are for web apps
idk, depends on what you are using do make the app
with python
Is there any good forums where people share websites they have developed and get feedback etc., (not reddit)
Or to show what they have created and get suggestions or positive or neg feedback etc.,
what are you using to make the gui?
tkinter @thorn igloo
For quick mostly attractive web gui components, how about Bootstrap? (https://getbootstrap.com/docs/5.0/examples/)
Is there any good forums where people share websites they have developed and get feedback etc., (not reddit)
Or to show what they have created and get suggestions or positive or neg feedback etc.,
Of course sharing in Python Meetups and Python Discord can be kewl. I used to participate in the Sitepoint.com community in my PHP days. Looking at it now, I don't see any tags for Python; however, I do see javascript, css, and html tags--that could be on your list to check out
he wants to make desktop apps
right, i am not too familiar with tkinter so i can't really say if it's possible to make a gui like that, but if you are good with html, css and javascript, you can make "desktop apps" with html css as the frontend part and use the eel library to connect your python code to the UI. or you can look at electron js i believe
not sure if electron js lets you use python
Here's a TKinter Tutorial, if that helps https://likegeeks.com/python-gui-examples-tkinter-tutorial/
yes it's possible, but it's basically just launching a chrome window for that app.
but it does what you're looking for i guess
Here are some episodes of the Podcast TalkPython where Desktop GUI apps are discussed with mentions of Tkinter. You might find some other package alternatives, too. https://talkpython.fm/search?q=desktop-apps-tkinter
@thorn igloo yes I watched a video how eel worked and its what I am looking for thanks mate
Question for Django: I'm looking to set a base.html template in the Project/templates folder. I've added the path to the TEMPLATES list in settings.py. However, I'm still getting an "outside file hierarchy' error.
Thoughts?
I've tried this in TEMPLATES so far:
'DIRS': [os.path.join(BASE_DIR,'templates')],```
Model.save() is probably returning None here.
I would assign instance explicitly:
instance = Model.objects.get(kwargs)
but even more preferably, use Django signals (pre_save signal), to run functions on a model's save event
anyone's up?
if we use flask as backend
how to pass the json reponse that i get from api to the front end
hey
can i help?
yes
@dusk portal just a pointer, donโt wait to ask people for help. Post your full problem so people can help you. Donโt just say โI need helpโ or โcan you helpโ
can i share screen
or screenshot's are enough?
@worthy relic

see last second ss path is also correct
then too
you need to have your media url in your path, try adding this to the end of your main urls.py
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
im on my phone rn so i canโt use code blocks but you get the point
oh
btw
if settings.DEBUG: why this?
@primal thorn
should i add this on my app where profile page is there on main proj
@primal thorn
\
mai project
ohk
itโs to see if the app is in debug more or not, also import
from django.conf import settings
as well
can you show your urls
oh
ok
from django.urls import path
from django.contrib.auth import views
from . import views as v_views
app_name='users'
urlpatterns = [
path('',v_views.register,name='register'),
path('login/',views.LoginView.as_view(template_name='users/login.html'),name='login'),
path('logout/',views.LogoutView.as_view(template_name='users/logout.html'),name='logout'),
path('profile/',v_views.profile,name='profile')
]
app
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('app1.urls')),
path('register/',include('users.urls'))
]
``` proj
add the code i sent in the bottom of your projects urls
you just needed to put your media file in your urls thatโs all
your appending the media url to the urls array
Using javascript's XMLHttpRequest
it's supported by all browsers (even IE) so no need to worry
Anyone here been able to load @font-face into Django in css file?
Here's a sample for submitting login data as form through a flask api to get it from flask using request.form
app/static/js/script.js
xhr = new XMLHttpRequest()
xhr.open("POST", "/api/login", true)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(`username=${user}&password=${pass}`)
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
// Here's the JSON response from the Flask API
let resp = JSON.parse(this.response)
}
}
app/app.py
... # Your previus Flask code
@app.post("/api/login")
def api_login():
print(request.form["username"], request.form["password"])
return jsonify({"status": "success"})
I know that @font-face can be brought into css regularly. How can this be done with Django?
I have uploaded woff font files into project/static/fonts.
css file has the following
@font-face {
font-family: 'Mont';
src: url("/fonts/font.woff2") format("woff2"),
url("/fonts/font.woff") format("woff");
font-weight: 900;
}
h1, h2, h3, h4, h5, h6 {
color: #444444;
font-family: 'Mont', sans-serif;
}
So, I'm pulling the font into the heading tags. The @font-face style is at the top of the css file.
I am seeing a 404 in the console.
GET /static/articles/fonts/font.woff HTTP/1.1" 404 1831
The files are there. But they are not coming through. What am I missing?
so I saw an application and when I pressed ctrl + shift + i I got the html console so how is it possible to have a broswer in an exe?
You want to make your website into an executable?
Or are you asking how a browser is an executable that you download?
i told you, the eel method opens a chrome window dedicated to your application, it's still html after all
or it could be electron js, either way it's html and that works on a browser
no it was an exe and not chrome or sth
I think its electron I see a folder here called electron in there
i'm saying the application essentially opens it's own chrome window, does that make sense?
idk
so how can I use frontend in python exe?
what do you mean?
you mean how to make a GUI for Python applications?
anyway, a lot of applications use Electron to run their frontend application with chromium
Build cross-platform desktop apps with JavaScript, HTML, and CSS.
no idea how to interact with that from Python, but there are probably some other libraries like that if you specifically want to build something with a browser integration
but there are lots of GUI libraries for Python
Hello Friends, I have a question about QueryDict type in Django.... So I have a form wich uses the select tag and so I can send multiple inputs with a POST.
I don't understand why python doesn't returns all the values from the dict when I try to read the key.... it returns only the last element on the list....
when I do dict['1'] It should return -> ['1_1', '1_2'] but it's only returning '1_2'....as a string.... any ideas why? is this a bug?
Alright never mind.... OMG why Django ๐ฆ so actually Django returns the last value from a list when you do it this way.....
https://code.djangoproject.com/ticket/1130
I hate it when Django objects work differently from Python objects.....
@white wigeon okey so electron is only with js?
electron is designed for javascript yes
with sphinx what is a page pattern? Is it the path to the file or is it pointing to the url
for context this is what im trying
html_sidebars = {
"**": ["search-field", "sidebar-nav-bs"],
"index.rst": ["home-navbar.html"]
}
ik that ** is every page but for a single page i dont seem to understand the page pattern concept
hi , can any one help how to pass values from one form to another and save all in django ?
def add_city(request):
data = dict()
if request.method == 'POST':
form = AddCityForm(request.POST)
city = request.POST.get('country')
duration = request.POST.get('duration')
if form.is_valid():
form = form.save(commit=False)
form.request.session['duration'] = duration
form.request.session['country'] = city
form = form.save()
data['form_is_valid'] = True
else:
data['form_is_valid'] = False
else:
form = AddCityForm()
context = dict(form=form)
data['html_form'] = render_to_string('cites/modal_1.html', context, request=request)
return JsonResponse(data)
def add_city_2(request):
data = dict()
if request.method == 'POST':
form = AddCityFormSec(request.POST)
city = request.POST.get('country')
duration = request.POST.get('duration')
something = request.POST.get('something')
if form.is_valid():
form.city = city
form.duration = duration
form.something = something
form = form.save()
data['form_is_valid'] = True
else:
data['form_is_valid'] = False
else:
form = AddCityFormSec()
context = dict(form=form)
data['html_form'] = render_to_string('cites/modal_2.html', context, request=request)
return JsonResponse(data)
class AddCityForm(forms.Form):
duration = forms.ChoiceField(widget=forms.RadioSelect(attrs={
'style': 'background-color: #FAF9F9', 'class': 'mb-3, form-check-inline'}), choices=DURATION_CHOICES)
country = forms.ChoiceField(widget=forms.RadioSelect(attrs={
'style': 'background-color: #FAF9F9', 'class': 'mb-3, form-check-inline'}), choices=CITY_CHOICE)
class AddCityFormSec(forms.ModelForm):
something = forms.CharField(widget=forms.TextInput(attrs={
'style': 'background-color: #FAF9F9', 'class': 'mb-3'}))
class Meta:
model = Cities
exclude = ['city', 'duration', 'something']
i want to input city and duration in first form , pass the values and display in second form , input something in second form and save all
without virtual environment I can't run django?
Sure you can.
what happened to using eel?
how?
ok then,
if you don't want to use that, i guess you can just use the standard python libraries for gui
I now use electronjs
how do you connect it to python?
not at all
I use electronjs!!
JavaScript with html and css
the bad thing is I have to convert my whole python code to js
wasnt your original post about connecting your python to an html gui?
ok
Looking for help using @font-face in a css file in Django. I have uploaded woff/woff2 font files into project/static/fonts.
css file has the following
@font-face {
font-family: 'Mont';
src: url("/fonts/font.woff2") format("woff2"),
url("/fonts/font.woff") format("woff");
font-weight: 900;
}
h1, h2, h3, h4, h5, h6 {
color: #444444;
font-family: 'Mont', sans-serif;
}
So, I'm pulling the font into the heading tags. The @font-face style is at the top of the css file.
I am seeing a 404 in the console.
GET /static/articles/fonts/font.woff HTTP/1.1" 404 1831
The files are there. But they are not coming through. What am I missing?
can i see your static folder structure?
how does flask google oauth work?
i can't find any website with good code (i copy-paste the code to get it to work, then edit it to be right for my use)
help there's some issue in my title
i even cant fetch title
it's null when i used self.content in str
you haven't created model User but linked a foreignkey to it
Sure. ๐
lol thats correct
it's django auth
model
url should be /static/fonts/font.woff
ty! I'll change and review.
This is an obscure one for a noob to Django.
for some reason it's trying to get /static/articles/fonts/font.woff
oops, typo
there
Should I place the fonts in the project dir? Or the app?
@thorn igloo do code at django too?
no i dont
i think the issue here is the url your app is using to get the fonts, not necessarily the directory
Yes...your suggestion prompted me to look at console output.
I'm new to Django but suspect there's a mapping issue. I'm moving the fonts first to see if i can align folder structure with what Django is trying to do
alright
Still not working...I'll try a server restart and hard refresh on the page. If this doesn't work I will have to look at settings.py and see if I can resolve through forcing a mapping

It's weird....because console shows mapping to the folder I've configured in url in css file. However, it returns a 404....
Nope...not working...Let me try and shift folder structure...
Is that url from the app? The app is "articles" I currently have:
create a fonts folder in articles and copy the font there
oh
Like this?
OK. I'll refactor back to static.
This is what I had....have restored to this:
@font-face {
font-family: "Mont";
font-style: normal;
font-weight: normal;
font-stretch: normal;
src: url('fonts/font.woff2') format('woff2'), url('fonts/font.woff') format('woff');
}```
it's not inside the articles folder
the articles folder in static
Like this?
yes, now what does it say?
OMG....MY HERO!!!!
I am SO GRATEFUL ๐
awesome
You're amazing....This was a WEIRD one!
Of course....oh my goodness...
Well, Django is awesome to learn...and it has some fun idiosyncracies. Loving it...but whoa....
I've literally been banging my head on that for about 4-5 hours
I can't believe I didn't think to move the fonts folder inside articles/static...face palm
i dont know why the /fonts/... url automatically looks in articles tho
I guess ours is not to wonder why, but to learn the pattern and accept it.
hhm, i mean you have to understand at some point in order to change it
In a way though...it's basically saying, look to the css file, and then assume fonts will have their own folder inside the same folder
Now, I'm wondering if I'll be able to centralize fonts, base.html and css files in the project folder...but so far all I've gotten is "outside folder hierarchy" errors.
I imagine that I'll either have to accept duplication for such files across apps, or I'll work out how to setup that mapping
Hi I just recently finished my school management app
Behold My Awesome Project!
It uses a three user system
Log-in with Pepanni and password alexdiana to access Primary admin
John and password favourgilead to access teacher admin
Sharon and password favourgilead to access student admin
It's my first project so I'd love to know what you guys think.
๐
Looks like a good start.
- If this really is a site for primary education then even the colors look appropriate. (^_^).
- I like the size of fonts, icons and buttons, which can be tricky.
- Clicked around and everything seems to be working nicely.
One thing I would think differently is Student List > Paid. While the switch works nicely as a GUI element, I don't like the lack of safeguards. This information is import and must be correct. I just clicked Luke's payment as $0, and I'm pretty sure he's going to get kicked out of school. hehe
Hello everyone,
I'm trying to make a function that retrieves the productStockLevel: "inStock" that is in the data variable on the auchan site on the page of an item.
I'm stuck because I can't access the data variable and I searched on the internet but I couldn't find anything or maybe I used it wrong.
For the moment I can only get the script[4] where my data variable is.
If someone can help me I would be very grateful I've been working on it for 1h30.
Translated with www.DeepL.com/Translator (free version)
code:
import requests
from bs4 import BeautifulSoup
session = requests.session()
def get_stock():
global session
productPage = 'https://www.auchan.fr/power-a-etui-de-protection-silhouette-pikachu-nintendo-switch/p-c1334312'
response = session.get(productPage)
soup = BeautifulSoup(response.content, "html.parser")
scripts = soup.find_all('script')[4]
print(scripts)
get_stock()
Hi
I have a quick question
Would anyone mind helping?
I'm currently using Hugo to build this website: https://github.com/MSJMathClub/msjmathclub.github.io
However, it fails to deploy, saying "Failed to unmarshal YAML: yaml: line 48: did not find expected key"
Does anyone know how to resolve this issue?
Hey Kylar. I'm new to this community and I did offer advice for your project. That said, I was looking in the FAQ for an answer to another question and I noticed this:
"Can we have a channel to show off projects...?
[...] You're welcome to showcase your projects in our off-topic channels..."
Just so you know--before we both get Mod-Clobbered. (>__<)
I'm working through a Django tutorial that is superb! I'm up to part 5 and so far I'm really enjoying this as an on-ramp to this framework: https://www.youtube.com/watch?v=UmljXZIypDc&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&index=1
In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic application running in our browser. Let's get started...
The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Django_Blog
Flask Tutorials to cr...
Hello, I am learning flask flashing. But I encounter a code like this, which is in the documentation https://flask.palletsprojects.com/en/1.1.x/patterns/flashing/
<!doctype html>
<title>My Application</title>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
{% block body %}{% endblock %}
But in the python file there is no get_flashed_messages() pass into this html file. How does this happened? How does Jinja2 read this function from nowhere?
I believe you can use the flash command in your Python. And then jinja to markup the Flash
But how does jinja read that function? Also I did not import it.
