#web-development

2 messages ยท Page 169 of 1

dense slate
#

Take a look at GraphQL sometime. I am using Django+GraphQL+Apollo and it is crazy fast.

late gale
#

Cool, I heard abotu graphQl but never used it before

#

and what's Apollo

#

never heard of that

dense slate
#

Apollo is a client that helps to cache data from the server, so you can deliver user requests even faster by reducing server requests.

late gale
#

oooh it sounds great

dense slate
#

Well, apollo has a client, and also a server and other tools.

#

But I just use the client with next.

late gale
#

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

indigo kettle
#

isn't nextjs also just react? They should be similar

dense slate
#

Next is like React+

#

It just optimizes a lot of things.

indigo kettle
#

I see

late gale
#

It's like React the future

dark violet
#

Anyone know any good Hugo themes?

rough tiger
#

is django as backend and reactjs for frontend possible? would it be a good combination for web app as a stack?

rough tiger
vestal hound
#

if you're new to JS/TS though

#

can consider Angular

opaque rivet
rough tiger
rough tiger
opaque rivet
#

NextJS (TS) + Django + Docker, killer combo

vestal hound
west peak
#

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

calm plume
#

Some of Next's features are amazing, and when paired with the power of Django, you can make some really nice things

opaque rivet
#

I think it's the meta of web development

#

actually, meta would probably use express

opaque rivet
#

trying to use selenium for webscraping - but I'm using a lot of time.sleep(). It feels really hacky. Is that normal?

vestal hound
#

there are APIs for waiting until something loads

#

which is what I think you want

opaque rivet
#

Yeah, for ajax elements loading

#

thanks, found the docs for it

arctic thicket
#

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.

wind walrus
#

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?
broken carbon
#

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

inland oak
#

frameworks Flask, Django and many others are an option for that

silver kraken
#

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 ?

chrome reef
#

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
]

cerulean badge
#

(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

wind walrus
#

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

royal cloak
#

hi all, if anyone has a good flask api tutorial, can share it with me, thank you.๐Ÿ˜„

native tide
#

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?

subtle sparrow
#

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

opaque rivet
opaque rivet
#

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?

topaz flower
#

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.

native tide
topaz flower
late gale
topaz flower
late gale
gritty cloud
#

Or add it to ur Procfile

broken carbon
#

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 ......

ember adder
#

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.

iron obsidian
#

@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?

mild bridge
iron obsidian
#

@mild bridge I tried to use filter_horizontal, but got a message it's only for many-to-many fields?

mild bridge
#

ah I must have misread

#

I'm not sure it is builtin in that case

iron obsidian
#

how do I override though?

mild bridge
iron obsidian
#

is there a list somewhere with all the builtin widgets?

mild bridge
#

cc: @ember adder on overriding frontend for field inputs, custom widgets are generally how it's done

iron obsidian
#

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

mild bridge
iron obsidian
#

I see. what exactly do you mean by point to it?

mild bridge
#

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"

iron obsidian
#

and the multi-select.html is just whatever? some html, some JS, some CSS? what's the API for widgets

mild bridge
# iron obsidian and the multi-select.html is just whatever? some html, some JS, some CSS? what's...

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

iron obsidian
#

but how does django take a value from it. What if my widget is not an input

mild bridge
#

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

iron obsidian
mild bridge
#

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

iron obsidian
#

I'm trying to find some

mild bridge
#

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

iron obsidian
#

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

mild bridge
#

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

iron obsidian
#

Thanks. do you know why the id_ + field name is needed?

mild bridge
#

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

iron obsidian
#

๐Ÿ˜„ 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?

mild bridge
iron obsidian
#

@mild bridge thanks. btw, unrelated, but how do you name a django project? this seems so random..

mild bridge
#

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)

iron obsidian
#

so what do you call the project? just "project"? "config"? name of company?

ornate flame
safe kindle
#

Hi

#

Which method should I use for a password change endpoint?

#

PATCH?

ember adder
native tide
#

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

ionic raft
#

I'm trying to run a Flask/SQLAlchemy application and getting Internal Server Error - details in #help-honey

burnt crest
#

I am using brython. I am trying to get user avatar from oauth2. I cant import discord. What to do?

grim helm
#

quick question with flask, is there a way to get other body data when submitting a post request?

gritty cloud
grim helm
#

that only gives me input tag things

gritty cloud
#

I'm not that good at flask, but in pretty sure request.form returns a dict

grim helm
#

yeah it returned an immutable dict containing 1 item

#

others just vanished

gritty cloud
#

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

grim helm
#

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

gritty cloud
#

the rest are disabled

#

i don't think disabled ones get submitted in the form

grim helm
#

:(

#

i dont want user to edit them

#

I just want them submitted..

gritty cloud
#

you can have them hidden

#

see this question

grim helm
#

ouh! that's neato

gritty cloud
#
<input hidden='hidden' name='foo' value='bar'/>
grim helm
#

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

gritty cloud
grim helm
#

ah.. fair enough

gritty cloud
#

then submit them with the form

grim helm
#

so the only way to interact with flask and html is forms

gritty cloud
#

you can also make a rest api with flask

#

and use javascript to interact with it

grim helm
#

mehhh that's overkill.. smth with jinja is what i needed

#

but yeah, this is a clean way

gritty cloud
#

yep

upper bronze
#

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.

graceful flax
#

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>

paper briar
#

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?

gritty cloud
paper briar
#

so ima have to learn php?

gritty cloud
#

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

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

gritty cloud
#

you need to know a bit before you can make stuff

paper briar
#

a lot lol

#

which is why i've resorted to 000webhost

gritty cloud
#

all ur errors are probably coming from the fact that your procfile is missing or has bad commands

paper briar
#

i think i got stuck at the procfile

gritty cloud
paper briar
#

:oooooooooooooooooooooooooooooo

gritty cloud
#

you just have to give it a few commands

#

they do all the work

paper briar
#

that seems amazing

#

thank you so so much

gritty cloud
#

yeah its kind of a miracle

paper briar
#

quite

full osprey
#

Guys anyone familiar with Django here?

#

@HaveMercyOnMe

gritty cloud
native tide
#

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')

languid raptor
#

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...

opaque rivet
#

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?

dusky moon
#

hey guys ik this is a python server but does anybody here have bootstrap knowledge?

proper hinge
dusky moon
#

for some reason my nav bar is working fine

#

however the dropdown button just isnt working

#

@proper hinge

proper hinge
#

Which version of Bootstrap?

dusky moon
#

latest version

#

@proper hinge

#

5.0

proper hinge
#

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

scarlet spoke
#

Can anyone please please please try answering this thread

#

does it have to do with js or something

proper hinge
#

Yes

#

In fact, someone just answered explaining that

scarlet spoke
#

thanks!

wooden ruin
#

are there any hosting providers that offer free hosting such as heroku that one would recommend to deploy a django project on?

inland oak
# wooden ruin are there any hosting providers that offer free hosting such as heroku that one ...

The Coding Den discord
?tag largehosting

Free:

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.
inland oak
#

if you can afford I would recommend using Hetzner for example, they provide quite cheap offers for testing/development

proper hinge
#

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.

inland oak
#

shrugs.
That's just rumours I saw somewhere. not having first experience with free tiers

#

I always choose just cheapest VPSes for testing/development

wanton sleet
#

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.

brazen stirrup
#

good day guys ๐Ÿ˜„

  1. is there some recommendation course for web develop(django) for Django beginners?
    I'm familiar with JS, TS, Java, Node, Rails.

  2. 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!

wanton sleet
#

This isn't a joke

#

I was wondering if someone could maybe explain this

frail sage
#

The syntax is really small and easy too

brazen stirrup
#

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

frail sage
#

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

round swift
#

How do I hide my sensitive data like smtp configurations and secret key in django projects if I want to host my website online?

forest dagger
#

or create one every 5 seconds

round swift
#

can you explain what is userdata?

forest dagger
frail sage
brazen stirrup
#

From JS, TS base team to Python + Django base team

frail sage
#

That must be a big shift

barren stratus
#

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()

outer nacelle
#

can anyone suggest me quick way to learn flask?

barren stratus
outer nacelle
#

thank you for your suggestion

vivid canopy
#

help me pls

frail sage
chilly wave
#

!d flask

lavish prismBOT
#

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.

native tide
#

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('-')

dusk portal
#

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

dense slate
#

@dusk portal it means that message becomes the value from your message input on your form after it passes through your form validation.

dusk portal
#

u mean which value

#

can u explain clearly plz plz @dense slate

dense slate
#

value of the input field on your form called "message"

dusk portal
#

ohh so why corey schafer made it message only

#

why not anything else

dense slate
#

I don't know Corey Shafer.

#

As to their intentions, I also don't know.

dusk portal
#

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

dense slate
#

form.clean_data is validated data from your forms.py

dusk portal
#

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']```
dense slate
#

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.

dusk portal
dense slate
#

How would you look anything up? You can query the DB.

dusk portal
#

yes in my admin page users are getting registered

dense slate
#

Do you know how to query the database to get a user, for example?

dusk portal
#

u mean login from those userrs

#

idk i have to learn that

dense slate
#

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)

dusk portal
#

oh

dense slate
#

If the user exists, return a message and don't create the user.

dusk portal
#

i am coding at django

#

from 5th of June

dense slate
#

That's ok, keep it up.

dusk portal
#

done this docs

#

then todo app

#

then contact page backend

#

1-2 more simple proj

dense slate
#

Good! You can also try django girls django tutorial

#

I found it super helpful.

dusk portal
#

ohh

#

ill doo it too

#

first ill do this corey's list within a week

vernal thistle
#

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?

dense slate
#

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.

vernal thistle
dense slate
#

Google django markdown library?

#

I only remember TinyMCE

vernal thistle
#

Is TinyMCE safe? I used it and it didn't even close unclosed tags.

dense slate
#

It might not be, I don't use those libraries. You'll have to check on that.

vernal thistle
#

All right.

#

Thanks

inland oak
#

apperently it is still in use

vernal thistle
#

Ah thanks I will check it out

opaque rivet
#

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?

vestal hound
#

normally โ€œmicroserviceโ€ implies โ€œcan be deployed independentlyโ€

#

so if you mean that, yes

inland oak
gritty cloud
#

Yo guys im using django-markdownify ijn my project

#

!pypi django-markdownify

lavish prismBOT
gritty cloud
#

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

opaque rivet
#

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?

native tide
#

Its fine)))

glossy scroll
#

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.

dense slate
#

@gritty cloud Is it not just applied like CSS throughout your html? Like just to the class attribute?

junior pecan
#

Can I get any link about beginner's tutorial?

gritty cloud
dense slate
calm plume
junior pecan
#

English

#

actually I am a beginner...so I want check out the tutorials

unreal heath
#

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

opaque rivet
#
'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?

shell raven
#

how do I apply CRUD functionality in django databases?

opaque rivet
#

so make seperate views which handle that.

shell raven
#

Ok

opaque rivet
unreal heath
#

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

opaque rivet
#

yes, so you can form variable paths like that, which you can then pass to your html template

silent ivy
#

How do I create a redirect link with django?

unreal heath
opaque rivet
#
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

unreal heath
opaque rivet
#

in what way?

#

@unreal heath

unreal heath
#

Itโ€™s still returning the string name and not the picture

opaque rivet
#

that will return the path to the file based off the variable, show some extra code

#

@unreal heath

graceful flax
#

In my Django project is it better to not use the Django ORM?

dense slate
#

@graceful flax What's the reason you ask?

graceful flax
#

Made a whole backend for an app, now came across articles saying the ORM is bad

graceful flax
latent cosmos
#

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

dense slate
quick cargo
#

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...

dense slate
#

Yea they make my life easier for sure.

fossil loom
#

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?

quick cargo
latent cosmos
naive rock
#

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?

proper hinge
#

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.

naive rock
#

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!!

arctic wraith
#

hello everyone

west peak
#

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

marble spade
#

How can I add a button that when I click it, it will print ("Hi") in console (Django)

arctic wraith
#

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!

arctic wraith
#

no

west peak
#

can i see your Ajax call?

arctic wraith
#

ok

#

it happens when i'm trying to add a new product

#

it's opening modal pop up forms

inland oak
marble spade
#

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.

views.py

    if request.method == "GET":
        print("hi")

how can I go about doing this?

inland oak
#

They offer things like throttling limit there for example too (to limit amount of requests from same ip against abuse)

arctic wraith
marble spade
#

even if its post tho, it doesn't really work

#

it refreshes the page

#

and it doesn't say "hi"

arctic wraith
#

do you want just a button that print hi ?

marble spade
#

for now, yes

#

don't wanna use js

arctic wraith
#

ah ok

#

you can use <a href="">....</a> ?

marble spade
#

I don't want to redirect to a new page tho

arctic wraith
#

and css to have like button

marble spade
#

eh

#

why when I refresh the page, does it run that function?

#

and like how can I stop that

arctic wraith
#

without refresh you want

#

with js is easy

arctic wraith
shut tiger
#

Anyone know how to change a flask.py from localhost to public?
On linux(ubuntu) with no monitor?

inland oak
#

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

shut tiger
#

oh wow, yes this looks good let me see if I can get it up

dusk portal
#

what should i do i dont like that way

#

from bla bla import views as xyz_views

elfin dragon
#

Please suggest some best free hosting for flask

elfin dragon
#

ping on reply

gentle jasper
#

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

proud lintel
#

Hi, I am facing this warning in ariadne, please help me.

#

ASGI 'lifespan' protocol appears unsupported

lilac heart
#

should i put routing inside my frontend (react) or my backend (django)?

frail sage
#

The backend

#

!d flask

lavish prismBOT
#

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.

lilac heart
#

i see

calm plume
#

Use whatever works best with what you're doing

lilac heart
#

but is there any advantages tochoose one over another?

frail sage
#

Backend's always better, if you're dealing with a big project

lilac heart
#

yea going for a big project

frail sage
#

That's what I prefer, personally

#

But it's your choice

calm plume
#

It's very dependent on 1, your preferences, 2, exactly what your project is

lilac heart
#

interesting

calm plume
#

Like, if your backend is just a REST API that's deployed on a different subdomain, you wouldn't do routing there

lilac heart
#

icic

radiant talon
#

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

stiff briar
#

I am trying to make a social media site.I have completed its backend and strugling in creating its frontend

#

Please

#

help

gritty cloud
#

if you on django, you can choose a framework or plain html and js

obtuse whale
#

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

gritty cloud
#

you would then need to incorporate an API for passing data to and from

#

the front and backend

gritty cloud
#

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

obtuse whale
obtuse whale
#
@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)```
gritty cloud
#

o ok

#

well this itself should be good

#

just make sure your files look liek this

#
main.py
templates
|___ cafes.html
obtuse whale
#

๐Ÿ™‚ i have the templates/static folder

gritty cloud
#

nice

obtuse whale
#

throws this py jinja2.exceptions.TemplateNotFound: /cafes

gritty cloud
#

you sure cafes.html is in templates?

#

and you haven't used any config

obtuse whale
gritty cloud
#

is this happening with other routes as well?

obtuse whale
#

no

#

perhaps i need to pass post/get methods to cafes function?

gritty cloud
#

no

#

first could you give me the entire traceback?

#

so we can determine whether its your fault or a bug

obtuse whale
#
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)```
gritty cloud
#

try using just render_template('cafes.html')

obtuse whale
#

i get cafes is undefined

gritty cloud
#

it looks like your url_for is tripping it up

obtuse whale
#

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?

gritty cloud
#

idk lol im pretty trash at flask

obtuse whale
#

re. the repeating thing :p

gritty cloud
#

o

obtuse whale
#

i could just throw it in a function

gritty cloud
#

i would do that

obtuse whale
#

=]

#

sounds good, thanks for the help

gritty cloud
#

np

#

maybe open a help channel for your template not found thing

#

ul find much more big brain people than me

obtuse whale
#

it's ok =] you've been very helpful, thank you!

latent cosmos
#

@obtuse whale use:
if form_on_submit(): return redirect(url_for('SOMEWHERE'))

rain delta
#

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

cerulean badge
#
# 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?

native tide
#

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?

gusty heart
#

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
#

@gusty heart selenium

#

for web automation, can be used for scraping too, a bit slow

gusty heart
#

@opaque rivet but selenium not need a browser driver and open browser? Sorry I new about that.

whole spear
#

Is there any API doc for Selenium 4?

bright lodge
#

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

inland oak
gusty heart
#

@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?

inland oak
#

htnl/css stuff can be handled with more lightweight solutions

#

And when site is intensive in javascript, better try finding their APIs first

gusty heart
#

Yes, I need load JavaScript, and this specific website dont have a public api...

native tide
#

Need help

#

@inland oak

#

anyone

calm plume
native tide
calm plume
#

Someone will help if they can

native tide
#

Do you have the ep?

calm plume
native tide
#

LOOOOOL

#

cya

inland oak
#

What is the ep
:thinking_dinosaur_emoji:

fast scarab
#

is web gui harder to develop for my app then normal gui??(ive never made any python gui's b4)

inland oak
fast scarab
inland oak
#

Tbh, perhaps desktop gui is actually easier to code may be

fast scarab
inland oak
#

I mean... simple desktop gui... can be requiring just several code lines

calm plume
#

Django is really nice, but it has more moving parts, so it may be harder to start off with

fast scarab
inland oak
#

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

calm plume
#

Web is definitely easier for people to access as well

inland oak
#

Yeah, removing installation issues too

#

95% of users have access to modernly updated browsers

fast scarab
#

ok im going webgui

inland oak
#

Just 5% keep using super oudated internet explorer or veeeeery early firefox/chrome

#

Recently caught user using forefox 4 .. while current one is 89

fast scarab
inland oak
#

Web gui can be made friendly to account even them

fast scarab
#

also can you have local web gui just on your masine and not for your network, right?(just makinng sure)

inland oak
#

For development of course

#

It can be made accessable by your localhost only

fast scarab
inland oak
#

Not for development purposes?

fast scarab
#

yes

inland oak
#

It can be too... But architecture of security for that is a separate topic :)

#

And backend and front-end protected with different ways

fast scarab
inland oak
inland oak
#

Basically user side is hell of unsafe

#

Best can be protected backend

hollow apex
#

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

outer apex
# hollow apex 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.

worldly shadow
#

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

outer apex
worldly shadow
#

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

dusk portal
#

any django dev rn on?

native tide
#

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...

inland oak
#

so... just store user session key in it ๐Ÿ˜‰ or something like that

#

just make sure you output valid, not outdated data

dusk portal
#

hey bro can u help @inland oak

native tide
dusk portal
#
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

inland oak
#

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

dusk portal
#

@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

noble wing
#

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 %}
inland oak
#

depends on which blocks your have in base.html

obtuse whale
#

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

native tide
#

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

latent cosmos
#

[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

peak kelp
#

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

native tide
# inland oak Read https://docs.djangoproject.com/en/3.2/topics/async/

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 blobpain

dapper solar
#

can anyone please tell me how i can connect my flask app with react frontend ?

dapper solar
#

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?

latent cosmos
inland oak
#

Flask should give data in json format

dapper solar
#

i see

safe kindle
#

Hi, is there any method to invalidate sessions in all devices using jwt (Django)?

#

For example, when changing passwords

inland oak
#

when they aren't matching, I deny jwt decoding

#

a bit silly approach tbh

#

but hey, it works

safe kindle
#

Haha ok, I'll keep it in mind, thanks

inland oak
#

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

safe kindle
#

Ohh, I see...

#

Thanks!

native tide
#

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 :)

real venture
#

i know its not community standard i just haven't changed it yet, going to do that here soon

dusk portal
#

anyone's up

mint folio
#

Do you have a question or are you just taking a poll?

dusk portal
#

LXD

real venture
#

any ideas on why it's not working

#

i tried switching the position of URLs and it still didn't work

dusk portal
#
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

rotund hornet
#

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

glossy scroll
ocean notch
#

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

inland oak
ocean notch
#

alright thank you

#

just wondering if there was something i was missing

rustic sky
#

(I'm still wondering about hit counter)

How should I go about my view/hit counter?

#
  1. ALL views (including refreshed)
  2. Unique views (by IP or Cookie, per day)
vernal thistle
#

In django, should I write my validator function for a textfield inside models.py, or should i make a separate file somewhere else?

arctic crow
#

I prefer to create seperate form.py
it can be done either way

small arrow
#

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)
dusk portal
#

app.secret_key = "Flask Good. Django Bad."
TGX_what1

#

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

small arrow
#

what framework are you using?

dusk portal
#

i want to share screen

#

or screen shot's

small arrow
#

Sorry I don't use it obviously. I am a flask guy logo_flask

dusk portal
#

ohh

small arrow
dusk portal
#

i have learned it from own , it's ezz and good flask is good

#

flask docs are worst bruh!!!

small arrow
#

The official docs are good!!

dusk portal
#

umm

small arrow
dusk portal
#

cant get from start

#

it's not summorized

#

see this

small arrow
#

read this yesterday. Its the worst docs I have ever read

dusk portal
#

LoL

small arrow
#

or I am not comfortable with the framework

dusk portal
#

if u r saying this then i will surely try django docs

small arrow
#

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

dusk portal
obtuse whale
#

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)```

quick cargo
#

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

small arrow
elder nebula
#

isn't flask just python?

quick cargo
#

you can only have one function with a given name

small arrow
#

okay then my bad

obtuse whale
#

ok ๐Ÿ™‚ thanks for the heads up

vestal hound
#

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

quick cargo
# vestal hound kinda nitpicky but

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?

vestal hound
#

if it was in global scope

#

this would be shadowing

#
a = 1

def f(a):  # this shadows a from outer scope
    pass
quick cargo
#

I guess true

#

I guess I just roll with pycharm's definition of it ๐Ÿ˜…

warped heart
#

with sphinx is it possible to link a specific element from the index page?

elfin wind
#

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

inland oak
#

you can use subheaders inside one page

sand glen
#

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

warped heart
#

do you know what a daemon is and what it does?

sand glen
#

doesn't it mean the thread ends when the program ends

warped heart
#

it runs your program as a background progress

sand glen
#

so i should make it daemon=False?

frail sage
dusk portal
#

@inland oak can u help ig u can only help ๐Ÿ˜ข

#

first unblock me TGX_what1

elder nest
#

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

warped heart
#

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'
supple kettle
#

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...

elder nest
#

Bc itโ€™s on repl it so you donโ€™t have to save

naive rock
#

What is persistent storage on Firefox?

warped heart
#

right click the reload button

elder nest
#

I cleared my cache and it worked

#

thx

warped heart
#

alr np

proper hinge
#

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.

primal thorn
#

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'])])

timber thorn
#

canI make a python script and style things with css and html???

#

like that โซ

thorn igloo
timber thorn
#

ok

#

and how do people design stuff like slider in an exe?

#

like slider animations

thorn igloo
#

idk, depends on what you are using do make the app

timber thorn
#

with python

raven cypress
#

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.,

thorn igloo
timber thorn
#

tkinter @thorn igloo

languid raptor
raven cypress
#

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.,

languid raptor
thorn igloo
# timber thorn tkinter <@!297433043709198336>

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

timber thorn
#

ok so its possible to connect python with html and css?

#

and make an exe

languid raptor
thorn igloo
#

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

languid raptor
timber thorn
#

@thorn igloo yes I watched a video how eel worked and its what I am looking for thanks mate

ionic raft
#

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')],```
opaque rivet
#
instance = Model.objects.get(kwargs)
#

but even more preferably, use Django signals (pre_save signal), to run functions on a model's save event

dusk portal
#

anyone's up?

cold estuary
#

if we use flask as backend

#

how to pass the json reponse that i get from api to the front end

cold estuary
dusk portal
#

ohk

#

so u know how to json?

worthy relic
#

@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โ€

dusk portal
#

can i share screen

#

or screenshot's are enough?

#

@worthy relic

#

see last second ss path is also correct

#

then too

primal thorn
# dusk portal 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

dusk portal
#

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

#

\

dusk portal
#

ohk

primal thorn
dusk portal
#

oh

#

but we can add like i added ^^

#

after urlpatterns end

primal thorn
#

can you show your urls

dusk portal
#

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
primal thorn
#

add the code i sent in the bottom of your projects urls

dusk portal
#

ohk

#

damn working how sir plz explain me @primal thorn

primal thorn
dusk portal
#

what is that

#

+=

#

why that

primal thorn
#

your appending the media url to the urls array

small arrow
#

it's supported by all browsers (even IE) so no need to worry

ionic raft
#

Anyone here been able to load @font-face into Django in css file?

small arrow
#

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"})
ionic raft
#

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?

timber thorn
#

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?

calm plume
#

You want to make your website into an executable?

#

Or are you asking how a browser is an executable that you download?

thorn igloo
#

or it could be electron js, either way it's html and that works on a browser

timber thorn
#

no it was an exe and not chrome or sth

#

I think its electron I see a folder here called electron in there

thorn igloo
timber thorn
#

idk

timber thorn
#

so how can I use frontend in python exe?

white wigeon
#

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

#

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

opal canyon
#

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.....

timber thorn
#

@white wigeon okey so electron is only with js?

white wigeon
#

electron is designed for javascript yes

warped heart
#

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

tepid jolt
#

hi , can any one help how to pass values from one form to another and save all in django ?

#

view.py

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)
#

forms.py

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

quick solar
#

without virtual environment I can't run django?

warm igloo
#

Sure you can.

thorn igloo
timber thorn
#

wasn't good

#

not what I was looking for

thorn igloo
#

how?

#

ok then,

#

if you don't want to use that, i guess you can just use the standard python libraries for gui

timber thorn
#

I now use electronjs

thorn igloo
#

how do you connect it to python?

timber thorn
#

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

thorn igloo
#

wasnt your original post about connecting your python to an html gui?

timber thorn
#

yes cuz I thought this is my solution

#

but it wasn't

thorn igloo
#

ok

ionic raft
#

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?

thorn igloo
tough tartan
#

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)

dusk portal
#

help there's some issue in my title

#

i even cant fetch title

#

it's null when i used self.content in str

west mulch
# dusk portal

you haven't created model User but linked a foreignkey to it

ionic raft
dusk portal
#

it's django auth

#

model

thorn igloo
ionic raft
thorn igloo
#

for some reason it's trying to get /static/articles/fonts/font.woff

#

oops, typo

#

there

ionic raft
dusk portal
#

@thorn igloo do code at django too?

thorn igloo
#

no i dont

thorn igloo
ionic raft
thorn igloo
#

alright

ionic raft
#

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

dusk portal
ionic raft
# thorn igloo alright

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...

ionic raft
thorn igloo
dusk portal
#

oh

thorn igloo
#

yea

#

wait, it needs to be in static

ionic raft
#

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');
}```
thorn igloo
#

the articles folder in static

ionic raft
#

Like this?

thorn igloo
#

yes, now what does it say?

ionic raft
#

OMG....MY HERO!!!!

ionic raft
thorn igloo
#

awesome

ionic raft
#

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

thorn igloo
#

i dont know why the /fonts/... url automatically looks in articles tho

ionic raft
thorn igloo
#

hhm, i mean you have to understand at some point in order to change it

ionic raft
#

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

cold latch
#

Hi I just recently finished my school management app

#

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.

#

๐Ÿ˜…

languid raptor
#

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
native tide
#

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()
remote dew
#

Hi

#

I have a quick question

#

Would anyone mind helping?

#

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?

languid raptor
# cold latch It's my first project so I'd love to know what you guys think.

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. (>__<)

https://pythondiscord.com/pages/frequently-asked-questions/#q-can-we-have-a-channel-to-show-off-projects-or-a-channel-to-find-people-to-work-on-projects-with

ionic raft
#

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...

โ–ถ Play video
noble wing
#

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?

ionic raft
noble wing
#

But how does jinja read that function? Also I did not import it.

ionic raft
#

Give me a moment...will look up a snippet I have...

#

I spent a couple of months with Flask...so have accomplished this before

#

OK....so here's how I used Python to send the flash...