#web-development

2 messages · Page 139 of 1

manic frost
#

I didn't mean inheriting from UserData -- I meant having UserData as a reference (i.e. composition)
Maybe you could have the project refer to UserData?

Another approach is to just have a single table for users, but to include a type of the user as a field (an Enum, not sure if something like this exists in Django's ORM model, I'm not familiar with django)

fluid fable
vestal hound
#

nested serialisers

wicked elbow
#

we're getting real fancy now, changing fsm fields through a web socket

#

@vestal hound i got real time notifications to work finally. took way way to long. im adding seen/not seen now so i can count and show number of unseen notifications. so much fun

vestal hound
#

this is what I did too

#

it was really nice when it worked

#

😂

wicked elbow
# vestal hound yeah

what did you use for the socket? cause what i used was insanely difficult to make work. and i dont fully understand whats happening behind the scenes

vestal hound
#

okay, more accurately

#

I didn't use websockets for notifications

#

only for chat

wicked elbow
#

how'd you handle database requests? i think theres another way to do what i did, but its the easiest method. and i can still run all the requests normally.

#

channels was easy, but doing stuff to the database, well that was not fun at all

wicked elbow
# vestal hound what do you mean?

how'd you connect your web socket to the database? it has to be done async. im using redis to as my channel layer, but it took a while to figure out how to use djangochannelsrestframework to watch the db for changes and echo to the proper people of the changes.

vestal hound
#

like

#

when one person sends a message

#

how to notify the recipients?

#

that's done through the channel layer

#

database is updated separately

#

in other words once you're connected to the websocket you only read from the database when entering a chat with someone else

#

(chat is a separate view for my app because it's not the main purpose)

#

(so you can only chat one person at once)

#

(and there are no toast-like notifications)

wicked elbow
#

no, thats easy echo the message is easy

#

yea, mines gonna be set up similar, but mines gonna keep all chats real time even when if your not in the chat.

#

for instance though

@action()
async def change_seen(self, pk, **kwargs):
  item = await database_sync_to_async(get_object_or_404)(Notifications, pk=pk)
  try:
    await database_sync_to_async(item.change_seen)()
    await database_sync_to_async(item.save)()
  except TransitionNotAllowed as e:
    raise ValidationError(e)
  return {'status': True}, 200
``` this is database updating through the web socket not done through a seperate request
vestal hound
#

hm normally I use it as a decorator

#

and have specific functions for business logic

wicked elbow
# vestal hound and have specific functions for business logic

the action decorator allows me to call it through the json thats sent between the front end and the server websocket. the .change_seen method is a method specific to notifications. the websocket, responds back with the updated status, and echos the update to the user thats subscribed. honestly insane how it all works. but since im gonna be bulk patching, its better to do through the socket then push a bunch of requests. but thats how ive figured out how to modify the database inside the websocket. can do creates and everything

manic frost
#

!rule 5 @deft hatch We won't help you circumvent a captcha. If the website doesn't want you to scrape it, then don't.

lavish prismBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.

crystal parcel
#

how do i get all the h5 href's from lower division and upper division courses but not include the graduate level courses

knotty burrow
#

-exc

#

-exec

#

@lavish prism

#

!

#

!exc

lavish prismBOT
#

A key part of the Python philosophy is to ask for forgiveness, not permission. This means that it's okay to write code that may produce an error, as long as you specify how that error should be handled. Code written this way is readable and resilient.

try:
    number = int(user_input)
except ValueError:
    print("failed to convert user_input to a number. setting number to 0.")
    number = 0

You should always specify the exception type if it is possible to do so, and your try block should be as short as possible. Attempting to handle broad categories of unexpected exceptions can silently hide serious problems.

try:
    number = int(user_input)
    item = some_list[number]
except:
    print("An exception was raised, but we have no idea if it was a ValueError or an IndexError.")

For more information about exception handling, see the official Python docs, or watch Corey Schafer's video on exception handling.

knotty burrow
#

!exec

#

!ec
print("hello")

#

!ecc
print("hello")

#

!exc
print("hello")

spare iris
#

Dude what are you trying to do?

coarse egret
#

have your ever used a h6 in html?

verbal coral
#

whats a good language for beginners learning back-end? (as in im super clueless)

inland copper
#

python-django

spare iris
#

You can do python and flask too

#

idk which is used more

verbal coral
#

when it says header in json does that mean its outside the curly brackets?

native tide
#

Take this example code how would I be able to use my custom url that I bought with this


if __name__ == '__main__':
    app.run(host='127.0.0.1 ', port=5001)

desert parrot
#

SORRY WRONG CHANNEL

native tide
#

No

vestal hound
native tide
#

. . .

#

I’m just trying to figure out how to host my flask app on my url

warped void
#

i think you have to host it on a server

#

there are sone tutorials in yt

native tide
#

.-.

vestal hound
desert parrot
native tide
lament sapphire
#

is there a Django and or Flask specific channel on this Discord server? thanks

vestal hound
eternal blade
#

Hi, in my django form there is text under each field saying

• This field is required.
How can I remove that text?. Thanks

oblique kite
#
urls.py
urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

admin.py
admin.site.register(somemodel)

models.py
class somemodel(models.Model):
    ...
    ...
    ...

hello guys ..
this is an example code .. when i tired to edit model in django admin panel, its throwing 404 error ..
how can i fix it?

nimble epoch
eternal blade
nimble epoch
#

so thats true

#

whats wrong with it

#

if you dont want to show the text under your fields just customize your fields and dont add their errors like => {{ form.username.label }} {{ form.username }}

oblique kite
nimble epoch
#

in the admin page?

#

cause i dont see any other urls app in your project urls

oblique kite
thorny nexus
#

when to use django and when to use flask

#

any tips guys

oblique kite
nimble epoch
# oblique kite Yes

not sure what the problem cause in admin page the django automatically rec the records. and when the its there so it shouldnt usually give error 404

thorny nexus
oblique kite
nimble epoch
brave ember
#

prettier extension in vscode make django html very dirty and so that it gives error

#

because it moves jinja tag on the newline

eternal blade
#

How can I play some animation while a process is happening?

glossy osprey
#

Thanks! I think I will go with writing the actual tasks as Django Management Commands, and then use Django-Crontab to execute those commands. It's not as "fancy" as Redis + Celery, but i (possibly naively) feel I am using the correct tools for the job. Celery, riding on top of Redis, just seems like total overkill for a backend management command. I feel it's more suitable for a massive pipeline of tasks, which my App does not have

native tide
#

What is the easiest way of deploying a flask app?

warm fractal
native tide
warm fractal
#

I tend to encapsulated apps as 12 factor supporting python package, install released artifacts in a container image and push those into a reverse proxy setup

warm fractal
native tide
#

will that work with websockets?

warm fractal
native tide
rotund parcel
#

I am planning to make a website that is data driven. Should I use React? Should I use Flask with React? Or Django with React? Or no React?

#

Wondering which of these web technologies works well together and is suited for Python.

#

Currently planning for React + Flask.

surreal thicket
#

use django if you know you're going to use a relational database with an ORM

#

otherwise there are a lot of options besides flask, although it's obviously very popular and actively developed, so it's not a bad default.

rotund parcel
#

Unfortunately, I am using SQLAlchemy but it's already built into my application with React + Flask and I'm not sure it would be easy to switch to Django's ORM or even Flask's Sqlalchemy ORM

surreal thicket
#

also what do you mean by "data driven"? the choice of web framework is probably less important than the API design between the frontend and backend

rotund parcel
#

What other options are there than Flask for coupling with React? Better options?

#

Data driven in that it's mostly going to be just viewing database entries and sending requests

#

not some beautiful web 2.0 interface or something

surreal thicket
#

i see, and what kinds of requests being sent?

rotund parcel
#

typical get requests with a couple integers

surreal thicket
#

and that would just return some data back to be shown in the browser?

rotund parcel
#

Yep, just running a query and returning it all in a table

surreal thicket
#

whenever i've worked on an application like this, typically what happens is that we define an API that the backend (the python server) implements, and the frontend (the react stuff on the webpage) can make asynchronous requests to that API in order to update and fill in data

#

so im not sure you need to care much about coupling between the web framework and the react part

#

and im not aware of any python web framework that has any specific niceties for working with react

rotund parcel
#

That is what I am planning to do. React is probably the right choice though? I've never touched it before

surreal thicket
#

react is a big complicated library

#

so there's a lot to learn

rotund parcel
#

Yeah that does worry me a lot.

surreal thicket
#

but, i think its a great way to design a webpage

rotund parcel
#

But it seems like the big thing to learn, so might be worth learning

surreal thicket
#

the main advantage of react imo is the "components" model

rotund parcel
#

I've already been learning Flask and SQLAlchemy, might as well add React to the mix

surreal thicket
#

and the other nice thing about react is that it gives you tools for dealing with the "current state" of the webpage in a nice way

#

if you're gonna do web stuff it's worth knowing imo

#

if you're already learning those tools, use those tools

#

you don't need the flask-sqlalchemy integration library

rotund parcel
#

React does seem like a big, scary library to learn

uncut rover
#

Hey

rotund parcel
#

Learn REACT in just FIVE MINUTES now that's what I'm talking about!

#

haha

surreal thicket
#

@rotund parcel i found that the official react documentation was very helpful

#

and if you want to really have fun, you can try using reasonml or rescript to write the frontend code instead of javascript 🙂

#

(jk thats more complexity than you need at this level)

rotund parcel
#

I do know JS already, so that's not an obstacle. I've always found transpilers to be weird.

lament sapphire
#

Why and how do I fix this? I feel it has somethign to do with my Path, however, I have installed Django and I did create a project successuffly in mu directory above.

What could be the problem here?

Bpower@tests-MBP ~ % cd Code_Master 
Bpower@tests-MBP Code_Master % cd Python 
Bpower@tests-MBP Python % cd Django 
Bpower@tests-MBP Django % python -m django --version
1.11.29
Bpower@tests-MBP Django % cd poll-100% 
Bpower@tests-MBP poll-100% % django-admin startproject
zsh: command not found: django-admin
Bpower@tests-MBP poll-100% % ```
rotund parcel
#

looks like your installer did not add the django-admin scripts to your path

#

If you use venv, you could do
python -m venv .venv . .venv/bin/activate pip install django

#

otherwise you need to maybe re-install django, or somehow get the django-admin script added to your path

#

You on windows, mac or linux?

#

zsh so I'm going to guess linux

#

You can probably do python -m django startproject

#

or try re-installing it
pip uninstall django sudo pip install django

lament sapphire
rotund parcel
#

most people recommend using venv. It's good stuff although annoying to have to also activate. It should handle all the installs and scripts for you nicely

lament sapphire
rotund parcel
#

I would do that, yep. Separate folder for every Django project with its own separate venv

#

venv isolates all your pip libraries too, so each project has its own isolated libraries

rotund parcel
#

It's very important for long term projects because over time libraries will change and you'll never remember which versions your project worked with

#

but pip freeze > requirements.txt remembers!

warm fractal
#

It's also important to do regular security updates of the pins just in case, nothing is quit like coming back to a overgrown maintenance backlog

rotund parcel
#

There's no prefect solution. I guess LTS is an attempt at a solution

lament sapphire
warm fractal
#

Pip freeze is pretty much pinning

warm fractal
rotund parcel
#

I hate going back to all my old projects and seeing "welp this would take a week to get back in running order..."

verbal bloom
#

I want to create an application so that when opened, it is sent to the server: "Hi I opened the app." How can I do this please tell me?

rotund parcel
#

Are you talking a python .py file that a user opens, or a web page they open?

verbal bloom
#

.py file

rotund parcel
#
import urllib.request

with urllib.request.urlopen("http://myremoteserver.com/hello?m=Hi I opened the app.") as f:
    print(f.read())```
lament sapphire
#

CommandError: 'poll-100-server' is not a valid project name. Please make sure the name is a valid identifier.

What is the convention for Django project names?

raw bronze
#

Hey guys!
I just wanted to ask what parameters can i pass in User.objects.create_user() in django. Is there any way i can make my own parameters (like if i want django to save a person's discord, how can i make discord= argument?)

fluid fable
# raw bronze Hey guys! I just wanted to ask what parameters can i pass in User.objects.create...

Another Django tutorial, here we are building a custom user model, as more often than not the default Django model wont meet our project needs. This tutorial will take you through building a model manager, building a new user model with extended fields and then show you how to customise the Django admin interface and finally perform some testing...

▶ Play video
raw bronze
#

Thanks!! 😊

lament sapphire
#

I'm at localhost 8000/polls and have this code in my view.py file:


from django.urls import include, path
from django.contrib import admin
from . import views



urlpatterns = [
    path('', views.index, name='index'),
    ath('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]```
Why is it givng me a page not found?
dry herald
#

I have been learning Django lately and I found that the learning curve is pretty steep. It feels like learning an new language as opposed to learning a library. I am not saying that Django is bad but I was surprised how much there was to go through.

rotund parcel
rotund parcel
dry herald
# rotund parcel I found it really easy to jump into Flask. So that's what I'm using

Yea, I thought about that too. I figured that Django's learning curve is worth it when I start adding more features like users, accounts, and database stuff. I do see the value it in so that's why I sticking with it. It's definitely not a "beginner friendly" but the docs are fantastic and it is straightforward when you do understand it. I am not really sure why people recommend it for new python developers.

I haven't used Flask, but I figured that at some point you need to add these features so the complexity and learning curve is going to be there at some point.

rotund parcel
#

Flask is easy to work with databases. I haven't done any accounts stuff though

#

I've always thought of Django as an everything framework it seems to handle everything about a website for you. Flask is smaller and more focused on backend work

lament sapphire
#

Thanks again

#
Page not found (404)
Request Method:     GET
Request URL:     http://localhost:8000/polls

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:

    admin/

The current path, polls, didn't match any of these.

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

And I'm at:
http://localhost:8000/polls

strong torrent
#

How would I secure my flask webhook so 3rd parties don't hack it

solemn flare
#

Super newbie question, very new to django: why is nothing returned in my GET request for PostListSerializer in this REST API? serializers.py: ```
class PostSerializer(serializers.ModelSerializer):

class Meta:
    model = Post
    fields = ('id', 'date_created', 'title', 'body',)

class PostListSerializer(serializers.ModelSerializer):

post_count = serializers.SerializerMethodField()
posts = PostSerializer(many=True, read_only=True,)

class Meta:
    model = PostList
    fields = ('post_count', 'posts',)

def get_post_count(self, obj):
    return obj.objects.count()```  models.py: ```class Post(models.Model):

title = models.CharField(max_length=100)
body = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)

def __str__(self):
    return self.title

class PostList(models.Model):
post_count = models.IntegerField()
posts = models.ForeignKey('Post', on_delete=models.CASCADE)``` PostSerializer GET works fine, but PostListSerializer returns []

glossy arrow
#

Guys

#

How would I implement websockets into my application?

modest agate
#

Hey everyone, i have a question, i am managing my django secret keys with env variables, but i want everyone that clone my github repo to be able to run it, so what can i do to protect my secret keys but let people run it?

indigo kettle
#

you mean just like the django secret_key?

#

or also api keys and stuff like that

lament sapphire
# bold imp This goes into urls not views

Should I have these both in there like this?

from . import views


urlpatterns = [
    path('', views.index, name='index'),
]

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]```
wicked elbow
lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @fathom cradle until 2021-03-06 01:46 (9 minutes and 58 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

cinder juniper
#

!ban 759553923253796884 Spamming "Furry Rap" youtube links in #web-development is not appropriate at all

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied ban to @fathom cradle permanently.

winter void
#

Hi, I have a flask design question. I have a working app, but I would like to refactor it. It's working reasonably well for my needs, but it's messy, and I want to learn different patterns. Should I ask my question here or open a help channel?

#

it's about routing and forms

#

pretty basic stuff (although not so basic for me)

#

I'll just go ahead and post here.

#

I have a little inventory app.
A user can add to the inventory by uploading a csv file from a form.
Data is validated and processed, compared to an existing database.
User is then shown a second form, where he can confirm adding his items or not. More information is displayed here for each item (such as if such item already exist, and and if so in what quantity, and so on).
At this step, user is required to add some custom information (such as storage unit identification, and other important things).
When submitted, data is processed once again, and everything gets added to database if nothing goes wrong.
Then finally, the user is redirected to some sort of receipt page, where he can see a summary of what he added.

#

(sorry for the long post. TL/DR, users add stuff to an inventory through a two steps process)

#

For my first version, code looks something like this (I made a quick overview):

#

`@app.route('/add', methods=['GET', 'POST'])
def add():
form1 = AddCSV() # WTForms for Form1

if request.method == 'POST' and form1.data:
    # validate and process csv data 
    # initialize and populate form 2 
    return render_template('add2.html', form=form2)

elif request.method == 'POST' and form2.data:
    # do stuff
    # return receipt
    return render_template('receipt.html', data=data)

return render_template('add.html', form=form1)`
#

So everything is in a single route... It's a bit messy. I put some helpers function in an external module. But I find it hard to find my way. What other pattern could I or should I use?

eternal blade
#

How cab I override django default logout url pattern?

marsh canyon
#

what do you mean by default logout url? the admin logout?

eternal blade
lament sapphire
modest agate
lament sapphire
#

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/Bpower/Code_Master/Python/Django/poll-100/.venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "/Users/Bpower/Code_Master/Python/Django/poll-100/.venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run
    self.check(display_num_errors=True)
  File "/Users/Bpower/Code_Master/Python/Django/poll-100/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 392, in check
    all_issues = checks.run_checks(
  File "/Users/Bpower/Code_Master/Python/Django/poll-100/.venv/lib/python3.9/site-packages/django/core/checks/registry.py", line 70, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "/Users/Bpower/Code_Master/Python/Django/poll-100/.venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "/Users/Bpower/Code_Master/Python/Django/poll-100/.venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
    url_patterns = getattr(resolver, 'url_patterns', [])
  File "/Users/Bpower/Code_Master/Python/Django/poll-100/.venv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/Bpower/Code_Master/Python/Django/poll-100/.venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 589, in url_patterns```
#

that's half of it....

#
  File "/Users/Bpower/Code_Master/Python/Django/poll-100/.venv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/Bpower/Code_Master/Python/Django/poll-100/.venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 582, in urlconf_module
    return import_module(self.urlconf_name)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 790, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/Users/Bpower/Code_Master/Python/Django/poll-100/polls_100/polls_100/urls.py", line 22, in <module>
    from . import views
ImportError: cannot import name 'views' from 'polls_100' (/Users/Bpower/Code_Master/Python/Django/poll-100/polls_100/polls_100/__init__.py)```
modest agate
# modest agate Both of them

For the django one i thought about leaving them to user to generate their own, but i am using Spotify rest API and i don't know how to manage them

wicked elbow
lament sapphire
# wicked elbow what error?

here is my views and url

urls.py:


The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
    path('admin/', admin.site.urls),
]

from . import views
urlpatterns = [
    path('', views.index, name='index'),
]

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]```
View.py:

from django.shortcuts import render

from django.http import HttpResponse

def index(request):
return HttpResponse("Hello, world. You're at the polls index.")```

lament sapphire
wicked elbow
#

merge this stuff

from django.contrib import admin
from django.urls import include, path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
    path('polls/', include('polls.urls')),
]
#

is the urls file in the same folder as views?

#

@lament sapphire

lament sapphire
#

I thought to merge that as well. Thanks giving this a run now.

#

well, it's still telling me I have this import error for views. That is super weird though.

wicked elbow
#

your looking for your views in the wrong folder is why your getting the error

lament sapphire
#

okay, added polls for the import, but now it's saying this:

#

oh

#

hmmm, that's obvious... lol, duh, well, they didn't say that

#

how would tha tlook than? I understand Path's, but not from the python syntax so much yet.

wicked elbow
#

what you should honesly have is this.

polls
....urls
....views
polls_100
....urls

then your urls should look like this
polls.urls

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

polls_100.urls

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('polls/', include('polls.urls')),
]
lament sapphire
#

it'd be
path(polls/ etc.?

#

plafee in the views path liek so

wicked elbow
#

your structure should look like what i wrote

lament sapphire
#

okay, I see

wicked elbow
#

polls_100
...wsgi.py
...asgi.py
...settings.py
...urls
polls
...urls
...views

thats how it should look

#

im guessing your folder names

#

you need to do your url file for each create app you do. and your base url file, the one you created your project with needs to point to that url file

lament sapphire
#

thanks a ton

#

that is clearing that up I think

wicked elbow
#

this is actually my first django project to, but i have 17 django "apps" running. lol ive had lots of practice.

wicked elbow
lament sapphire
#

I got that now. weird I missed that. but I'm partly blind so that type of detail I miss sometimes.

wicked elbow
eternal blade
#

Hi, I am trying to display a message if the credentials are incorrect, This is my code```py
def loginPage(request):
if request.user.is_authenticated:
return redirect('home')

else:
    if request.method == 'POST':
        username = request.POST.get('username')
        password =request.POST.get('password')

        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            
        else:
            messages.info(request, "Username OR password is incorrect")

    context = {"form":form}
    return render(request, 'registration/login.html', context)
This is my html code to display the message ```django
                {% if message %}
                {% for message in messages %}
                    <p id="messages">{{message}}</p>
                {% endfor %}    
                {% endif %}        
``` But the page refreshes instead of displaying the message when incorrect credentials are entered. Thanks
heavy ferry
#

any good resources for django?

lament sapphire
nimble epoch
raw bronze
#

i cant load images in django.. i am getting 404

stuck palm
#

Are Javascript and Flask/Python directly comparable? As in, if I wanted to try and replicate a functional website built with javascript, could that be done between Flask and python or do I need to be learning Javascript as well as Python?

orchid oasis
#

you cant use python client side, well you can, but not well

timber glacier
#

Is it in a grid?

random lava
#

Hi, quite a specific problem i have.
Im currently using mongodb for a flask app and was working fine on my local ip.

However, i tried deploying my app on pythonanywhere and pymongo is throwing this error:

pymongo.errors.ServerSelectionTimeoutError: No replica set members found yet, Timeout: 30s, Topology Description:

Anyone come across this before ?

lament sapphire
lament sapphire
#

Can you share your html with us? I'll help you

formal axle
#

Anyone know how I could learn backend, ik I’m learning flask and all but like is there anything else except APIs that I have to learn

formal axle
#

Alr lol

#

I’ll learn django instead

lament sapphire
lament sapphire
#

so you would liek Feed and Profile inline?

formal axle
#

Thanks

lament sapphire
#

well I also just fixed it for you using flex

#

however, I could show you the inline version too. Although you could mak those buttons inline without a container, I recommend you always use some sort of container for soemthign like that.

#

are you abel to see what I did just now?

#

one sec, wodneri if it'll let me save the pen.

#

lol, not good at pens..

Here place this html:

  <button class="feed padding friends2"><a href="/feed">Feed</a></button>
    <button class="profile padding friends2"><a href="/home">Profile</button>
</div> ```

Then repalce this css:
```/*Feed*/
.container {
  display: flex; 
}
.feed {
  background: #ffe599ff;
  text-decoration:none;
  font-size: 110px;
  Border: 4px solid black;
  font-family: 'Comfortaa';
  color: black;
}
.padding {
  padding: 10px; 
}

.profile {
  background: #fff2ccff;
  text-decoration:none;
  font-size: 110px;
  Border: 4px solid black;
  font-family: 'Comfortaa';
  color: black;
  text-align: center;
}```
#

I know you wanted thigns centerd as well, however, you start small and extend out from there.....

#

That is flex, if you want inline, then on teh container, replace fles with Block.... and then add disply on .padding and add inline-block

#

well, if you made it work with that, great, however, that's just using too much margin in my opinion, it' snot needed.

native tide
#

yo

#

ima not advertising but lmao i make some good websites tho-

balmy elbow
#

I needed web scraping help
how to avoid values of tags to be "loading" while web scraing in requests module in python
??

#

see this

#

:

#

Here , in JHU's website , the statistics does take time about 0.5 secs to load and until it loads , it returns the term "loading"\

#

🙁 🙁 🙁 🙁🙁 🙁 🙁 🙁

bold imp
# winter void So everything is in a single route... It's a bit messy. I put some helpers funct...

The only thing that comes to mind for me is just maybe separation into different views but if it seems to be working well for you atm and performance is good I honestly don't have any other ideas. I'm running into the same wall with django as well where I feel there would be better ways to do things but I haven't discovered them yet. I hope someone more knowledgeable answers you since this is the only normal question I've seen in here in forever

wicked elbow
#

i found a django only server, this should be fun. maybe theres people in there that can answer my questions

lyric raft
#

im making a website on django and im having some issues understanding how to implement a database
do i have to create a class for each table on the models.py file? even if im using a cloud based mysql database?

wicked elbow
lyric raft
#

thanks alot!

native tide
#

Hi, I'm trying to learn how to use beautiful soup to output an HTML that has my own HTML code, followed by the content that's found by beautiful soup, and then my own HTML code again. So far, I'm able to get the beauitful content on its own by writing the soup into an html file. Could someone help/guide me to some resources?

formal axle
#

anyone know how to make the hieght of the page responsive to

#

because when I change the width everything is fine but if I change the height it isnt responsive

stable nacelle
#

When designing a REST API, what is an endpoint like POST /users (that creates a new user) supposed to reply? not really sure if any data is needed here, so I'd probably just reply with 204 (No Content) or something like that?

quick cargo
#

204 has the potential (atleast in my experience) to confuse things like Postman when they have nothing to not navigate to etc... which ends up leaving it hanging

#

if this is for a website using a POST request on per say a Form you will want to render back to the original page

stable nacelle
#

no, it's just a JSON REST API, decided to return 200 + the userid and name that was created

#

I do have 204 on a DELETE endpoint though, should I change that to 200?

quick cargo
#

its mostly depends on your use case

#

but you should? be ok

manic frost
#

'REST' doesn't define any protocol or data format 🙂

#

so do whatever makes more sense -- an id of the resource, the inserted resource itself, no data etc.

#

What would be the reason to use a more nuanced response like 204 as opposed to 200? Different caching policies?

trim token
#

Hi peeps. Can someone tell me about some good resources for django beginner ?

manic frost
elder sentinel
#

i'm coding a web with django and react. When i get the first view i get a blank page instead of the word testing

#

anyone has an idea on what could it be?

valid girder
#

Hi folks! I built a starter project creator for Django - https://github.com/imagineai/create-django-app
This whole project is auto-generated from a config file. Also you can go further than typical starter projects and even generate source code for your Django models, APIs (both REST and GraphQL) etc. Plus the code comes with 100% test coverage (the tests are also auto-generated).
Would love any feedback if you try it...and if you do find it useful, please star us 🙂 Look forward to see what you can imagine with this!

fickle fjord
#

I have these squares but with my css code they are supposed to be triangles why is this happening?

#

.triangle-red{
position: absolute;
width: 659px;
height: 653px;
left: 120.34px;
top: 423px;

background: #C84242;
transform: rotate(20deg);

}

#

here's the code

wicked elbow
#

i mean you can use image trickery, but i dont know how you make elements that are squares other shapes.

vestal hound
wicked elbow
sturdy yoke
#

Hello m new to web dev can someone tell me which lang i should choose for backend?

wicked elbow
wicked elbow
toxic flame
#

Hi guys I'm back for some advice, i would like to learn how to use any frontend framework ( react, vue, angular ) with django, that supports authentication and stuff like that. Is there any documentation / recomendation for resources corresponding to this?

#

Also is there a way to use django as a "seperate" api while checking the boxes above? ( auth )

wicked elbow
vestal hound
toxic flame
#

Yea i was planning on hosting django api on another domain / subdir while using a fronted framework for everything while using json to pass data and communicate

wicked elbow
toxic flame
#

But, I was hoping for some preview / pre-knowledge before diving into it.

sturdy yoke
wicked elbow
#

django is open source, flask is too

sturdy yoke
#

is any one here who contributed in open source??///

sturdy yoke
wicked elbow
wicked elbow
toxic flame
#

yea

#

i am asking where did u learn that

wicked elbow
#

theres like an 7-8hr video series on youtube for a basic application. let me see if i can find it again. theres some issues with it though, try to get the versions he uses or you'll run into some complications

toxic flame
#

Please

#

Maybe I'm just overthinking it

wicked elbow
toxic flame
#

Oo

#

Nice

#

.bm 817960731634958418

wicked elbow
#

i believe thats what i watched anyways

toxic flame
#

thank yku

#

thank you

#

I just need to read some stuff about authentication with django as a rest api

fickle fjord
#

@wicked elbow change to f string lemon_enraged

#

f"Name is {Kendal}"

wicked elbow
toxic flame
#

:o

wicked elbow
wicked elbow
#

not a clue, but this is excessive.
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
just do,
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
so do the exact same thing

#

since your not allowing zoom, then you only need to set the initial-scale

#

yea not a clue about the rest of the metas. i havent launched my site yet, so really dont need any of the rest of that

vale charm
#

i can still zoom with CTRL + scroll

#

is there any way i could remove that

#

no right?

carmine swift
#

should be able to disable with javascript

vale charm
#

how

carmine swift
#

not sure but i can try googling an answer

#

you'd have to experiment though the many possible answers

#

might be a bit difficult to find a solid answer

#

as not everyone uses the same browser

#

are you trying to lock your site to a certain zoom %?

vale charm
#

i mean yea

carmine swift
#

is it to prevent things from looking disproportionate?

vale charm
#

i mean i just dont want ppl to zoom or like change anything

#

i just want everyone

#

except me of course the developer

#

to look at the same thing

#

what it they zoom

carmine swift
#

I think the effort you are attempting to put into disabling zoom is a bit much. most people dont really zoom into things unless they have bad eye site i feel

#

what are you making a find waldo web app or something?

#

try out that javascript but you might need to continue adding scripts to prevent every possibility

#

dont forget people have different browsers. Some up to date and some not

vale charm
#

how can i remove that if u know

carmine swift
#

might be something to do with your html. set body margin to 0

#

or actually

#

that looks like a border

vale charm
#

it was never before there

#

except when i zoomed

carmine swift
#

do you have btn-group as the class for that attribute holding 'Discord'

#

looks like a border

#

that whole thing a button

#

?

vale charm
#

yes but as i told u

#

it happens on zoom

carmine swift
#

So this whole zoom thing is to prevent that slight gap from showing?

#

One sec

#

use something like this to remove the top of the border border-top: none;

#

if a border causing issues on your site is pushing you to find ways to prevent zoom reconsider how you built the site in the first place

#

especially if its a banner you are having this fight with

#

is that something you want? change this in btn-grp - > border: 1px solid #dbdbdb; - > border: 5px solid #dbdbdb; or something larger than one so it doesnt seem like a small gap

#

but I think you might want to learn a bit more html

#

if you went to the extent of attempting to disable zoom because of a border

#

you might enjoy using stylesheets like boostrap from here

#

or here

#
#

Then I suggest learning more

#

you are on the right path though!

#

that excitement of making things your own is what will get you to learn

#

keep at it

#

I will try not to

#

look into the input attribute

#

Yes

#

This is where you will have to learn more as I suggested

#

You can keep your button but place a input attribute within but then you have the affects of a button with an input ontop. might be better to keep both grouped inside a div

wicked elbow
carmine swift
#

@vale charm shouldve kept the messages and not delete them! someone else couldve found it useful

wicked elbow
#

@toxic flame hey i thought of something about that tutorial though you should know. itll teach you class based components, but modern react uses functional components with hooks. just keep that in mind. its still the same basic idiology between the two. and i can show you the differences after you learn

vestal hound
#

my bad...

wicked elbow
# vestal hound my god I totally forgot

lmao haha. you probably woulda missed it... it took some deep thinking to figure it out. been stuck on it for 2 days now. even switched my db from sqlite3 to postgres thinking it was a limitation of sqlite3 to be observed twice

#

so its all good. this stuff is still way over my head. and theres no documentation at all. so its all trial and error solving it

#

but holy smokes the performance increase is insane. i didnt realise that sqlite was slow at posting untli i switched to postgres

toxic flame
wicked elbow
toxic flame
#

hmmm good point, ill start learning react tomorrow

#

i learned vue and express in 4 days so it wasnt much time wasted

#

4 days with 4 hours studying daily

#

16 hours in total

lavish lily
#

i am new in python i wanna learn it any best source on utube where i can be perfect

lucid vine
#

Hello, does anyone know of any good resource on best practice with refreshing JWT tokens? I don't want the user to constantly have to keep logging in, but also don't want to make the token be able to last forever by allowing them to constantly refresh it.

lavish prismBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

opaque rivet
#

React is a really quick learn

#

I felt like I've stagnated what I can learn within it

#

But the libraries are endless, so I guess the majority of your time is learning that.

opaque rivet
cerulean vapor
toxic flame
#
DEV Community

This article provides a walk-through of a project that implements session authentication for a web app that uses Vue.js and Django REST Framework, looking at both email/password-based login as well as social login

#

It does say vue, but the logic does apply the same to any other frameworks

compact flicker
#

what's the bare minimum system requirement for Django...?
Can I run It on a 512 MB pi board...?

toxic flame
#

depends on what you are doing with django

compact flicker
#

Rest Framework, controlling 5-6 microcontrollers by async...

compact flicker
toxic flame
#

i dont think that's enough imo

#

but who knows, it could, you can have a simple test using heroku since their free plan is also 512MB if I'm not mistaking and see if it breaks their "dyno"

compact flicker
#

@toxic flame Thanks, man...
will give that a try before making the buying decision...

toxic flame
#

yea you don't want your pi exploding 2 days in

opaque rivet
toxic flame
#

It's not mine, just wanted to share it

opaque rivet
#

i know 😄 thanking you for the recommendation

#

i've been moving more to session auth for my react frontends, in my opinion it's much better, and enforces CSRF protection and has more support for login and logout. previously, all that would have to be implemented manually.

#

makes me wonder why people use token auth instead of session auth entirely.

rotund parcel
#

Is Bootstrap the most popular CSS styling tool? Are there others with similar purpose worth learning that integrate with React?

hoary brook
rotund parcel
#

There are a few out there, like Semantic UI too. I'm wanting to learn the most popular to maximize job attractiveness. Bootstrap is on top?

carmine swift
#

pretty much used almost everywhere

#

you can customize it and make a unique layout for yourself

#
tulip beacon
#

guys, how should I make a video conferencing webapp

rotund parcel
#

Like Zoom?

tulip beacon
rotund parcel
tulip beacon
tulip beacon
tulip beacon
rotund parcel
#

The Zoom Developer Platform is an open platform that allows third-party developers to build applications and integrations upon Zoom’s video-first unified communications platform. Leverage APIs, Webhooks and SDKs to build custom applications and super-power your business with a powerful collaboration suite.

tulip beacon
#

@rotund parcel can you recommend any tutorials which might help?

#

can anyone suggest a good tutorial to make a webapp like zoom

summer wyvern
#

well

#

thats a very big project

rotund parcel
#

Why do you want to build Zoom?

summer wyvern
summer wyvern
summer wyvern
rotund parcel
#

I can't imagine anything I create will ever be more secure than Zoom.

tulip beacon
summer wyvern
#

why dont you show the error

rotund parcel
#

Thinking an app you create is going to be more secure than an app that has teams of developers is a rather tall ask of one's self.

rotund parcel
#

For all I know half my stack has vulnerabilities. I have no idea how I'd even verify such a thing, but I guarantee that Zoom has many developers working just on security and making sure everything is secure.

summer wyvern
#

trying to make a version of zoom more secure than zoom by yourself is like stacking pencils on top of each other, tip by tip

tulip beacon
tulip beacon
summer wyvern
#

yeah

#

but you need a proper startup

#

and a small team

#

at least

#

of two people

rotund parcel
#

It's like asking someone to build a bridge that is more stable than the Brooklyn Bridge, but they've never built a bridge before. It's not impossible, but it's unlikely.

summer wyvern
#

yeah

tulip beacon
#

hey, anyone interested here?

summer wyvern
#

not really

tulip beacon
#

anyone else

rotund parcel
#

there are literally hundreds if not thousands of Zoom-like sites and apps in existence.

summer wyvern
#

im not the best with javascript

rotund parcel
#

I would bet there are thousands

summer wyvern
#

microsoft teams

carmine swift
#

its a big project

summer wyvern
#

lifesize

rotund parcel
#

You're just naming the big ones too. There are hundreds of tiny ones out there

summer wyvern
tulip beacon
#

yeah, but zoom has beaten all of them even though its security features are not that good

summer wyvern
#

use one that has the security you desire

carmine swift
#

do you have any experiences in creating software?

tulip beacon
summer wyvern
#

what experience have you got?

tulip beacon
carmine swift
summer wyvern
#

you need to be an expert at js

carmine swift
#

its lots of planning

summer wyvern
#

this project is mostly javascript

tulip beacon
#

I'm good at python and java

summer wyvern
#

and a bit of html and css for the actual frontend

carmine swift
#

you asked how to use the zoom api though

summer wyvern
carmine swift
#

do you know what apis are?

tulip beacon
#

oh

summer wyvern
#

best backend for this is js

rotund parcel
#

In conclusion, a Zoom clone might be a fine test project for a portfolio showcase, but it's not really going to be the start of a real business app. It's also going to be a difficult and fiddly showcase piece, with a lot of little pieces work that won't show very much when it's finished.

tulip beacon
tulip beacon
rotund parcel
#

One word: Plastics.

carmine swift
#

have you made projects to showcase

tulip beacon
carmine swift
#

i feel if youre asking what you can make that will be successful then you need to gain much more understanding and experience about several things

tulip beacon
#

I mean I'm scratching my head to get good ideas, but most of them are already made.....

carmine swift
#

hey man thats how we all learn though

#

just make a video chat app

#

learn what it takes to make it

#

from there you will grow

#

dont try to make something that beats zoom

#

try making something to learn how such app is built

tulip beacon
#

I'm trying to find new ideas

rotund parcel
#

Make a to do list. connect it to a database.

tulip beacon
#

some idea which no one has done...

carmine swift
#

you want to do something no one has done

#

ok

tulip beacon
carmine swift
#

but do you know how to do things like create a chat box

rotund parcel
#

Make a news aggregator that visits your favorite websites and gets the latest news for you and displays it in nice cards

carmine swift
#

for your video chat

carmine swift
#

gotta learn the foundations of your app

#

outline your projects features and what you want to accomplish

#

start from there

#

asking what you can do that no one has done is a difficult question

#

if i knew i wouldnt tell ya and i would do it myself 😏

tulip beacon
#

I always wanted to make an ar app which is useful for educational purposes

rotund parcel
#

Nah there's a million apps no one has time to make

carmine swift
#

try it!

#

make it and learn augmented reality!

#

use something you learn from that and create a video chat based on that

tulip beacon
rotund parcel
#

I would make something that aligns with your other interests

#

That's what motivates me

tulip beacon
carmine swift
#

yeah if thats part of your interests sure

summer wyvern
#

look at the most popular apps right now

#

and study them and what they do

carmine swift
#

write down what they all do

summer wyvern
#

find what to make with your studies and notes!

carmine swift
#

and what YOU think should be added on top of that

#

dont code without planning for a project like this

rotund parcel
#

Make a web app where people can upload and rate people's recommended Portfolio Showcase Projects! And link to tutorials to help people make them!

carmine swift
#

you'll probably end up halting yourself mid way thru

tulip beacon
tulip beacon
#

what do you guys think about AI ideas?

summer wyvern
#

make a social media

#

thats different

carmine swift
#

one where its dog videos ONLY

#

id sign up aha

tulip beacon
summer wyvern
tulip beacon
summer wyvern
#

i have cynophobia

carmine swift
#

see how its hard to come across something everyone likes?

tulip beacon
carmine swift
#

i think you should build a simple video chat with augmented reality since you said its something you want to try (the ar part) get that working

rotund parcel
#

Yes. You should make an AI Zoom clone

carmine swift
#

run some tests and start from there

carmine swift
#

hmm make a video chat where i can place a 3d model in the background and as i move it stays put or something

tulip beacon
#

ar video call app, should they some thing which project there whole body or something like that

carmine swift
#

yeah i want to flex the dinosaur i own in the background of my video call

carmine swift
#

you get it though try it out

tulip beacon
#

what about making an AI car and pedestrians tracking app?

rotund parcel
#

Yes

tulip beacon
rotund parcel
#

you tell me

#

Part of the project is to figure out why the project exists.

tulip beacon
tulip beacon
#

what do you think we could do with an ai tracking app?

rotund parcel
#

What couldn't we do with it?

#

Sell to the government probably

carmine swift
#

make that video call, learn about ar, learn more about your video chat while adding all sorts of things to make it secure for the user

#

start from there

tulip beacon
#

or I have another idea of making flying car transportation..

tulip beacon
#

and has power pads to charge every 200 metres

summer wyvern
#

nice

tulip beacon
#

so, no worries for battery low situations

rotund parcel
summer wyvern
#

in 4th grade my friend invented an idea for selling working deloreans

rotund parcel
#

They want to hear about your car plans

rotund parcel
#

It's a good idea isn't it?

#

It could even be like a Leetcode but for portfolio showcase items

lime mist
#

I'm using an asgi socketio server. The server takes base64 sting on an event emit from the user, does OCR and returns the text in the image to the user. My question is about the function I'm using to do the OCR. It's not an async function. What i wanna know is do i need to make it async so when two users try to get text on the same time the server solves them at the same time and not one after the other or simply defining a function in this case will solve them in parallel anyway

#

Question Summary: I have an ASGI SOCKETIO SERVER that does OCR. The function that doea OCR is currently normal function. I wanna achieve parallel solves under situations where the server is hit multiple time at the same time. So what will work better for this OCR processing, sync or an async function?

rotund parcel
#

@lime mist What performs the OCR logic?

lime mist
#

I have a function that first convers received base64 string to image, makes it grayscale using opencv and then extracts the text by running a python tesseract function. Then the obtained text is emitted as a response to that user @rotund parcel

#

I'm confused if a sync function can be accessed by multiple async functions at the same time

rotund parcel
lime mist
rotund parcel
#

ProcessPoolExecutor will run your function in a separate process so you just need to adjust your function to be pure and without side effects.

lime mist
#

I've worked with threads but never with processpools.. this should be interesting

ocean fjord
#

Hello, i am trying to do something with Vue.js and django and when it comes to serializers it throws this error

lavish prismBOT
#

Hey @ocean fjord!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

ocean fjord
rotund parcel
#

looks like you need to specify a basename for:
router.register('products', 'ProductsViewSet', basename="my basename here")

ocean fjord
#

oh

#

thank you

rotund parcel
#

I've never used django or vue.js before

ocean fjord
#

i am relatively new to this soo i dont know a lot about it

rotund parcel
#

I am newer than you.

ocean fjord
#

hehe

rotund parcel
#

I'm just okay at reading error messages

ocean fjord
#

Give me that power

#

is it possible to learn that power

rotund parcel
#

It comes from a lifetime of generating lots of errors.

ocean fjord
#

HAHAHHAHAHAHHHAHA brooo dont be to harsh

rotund parcel
#

at least this one was readable. Some libraries have terrible error messages

ocean fjord
#

yup

#

but now i get this error

#
File "D:\projekti2021\backend\products\urls.py", line 8, in <module>
    urlpatterns = router.urls
  File "C:\Python39\lib\site-packages\rest_framework\routers.py", line 77, in urls
    self._urls = self.get_urls()
  File "C:\Python39\lib\site-packages\rest_framework\routers.py", line 338, in get_urls
    urls = super().get_urls()
  File "C:\Python39\lib\site-packages\rest_framework\routers.py", line 236, in get_urls
    routes = self.get_routes(viewset)
  File "C:\Python39\lib\site-packages\rest_framework\routers.py", line 152, in get_routes
    extra_actions = viewset.get_extra_actions()
AttributeError: 'str' object has no attribute 'get_extra_actions'
rotund parcel
#

at this point you should probably pull up the API for router.register because you're probably doing it wrong

ocean fjord
#

i am following some kind of tutorial

#

it seems not to work

rotund parcel
#

it looks like the second argument for router.register is supposed to be an object, not a string

#

so: router.register('products', ProductsViewSet)

ocean fjord
#

yeyeye

#

thank you

#

i just saw that

#

FINALLY

#

thank you ❤️

wicked elbow
#

figured out how to do it in branches as well. so ive got notifications, message groups, and messages coming soon all pushed through sockets

steep compass
#

Hello. I'm working on a very small Flask project that basically lists some names with numbers to serve as an API. However, when I hosted it in Heroku, the data was not persistent and got deleted after some minutes/hours... why could this be happening?

rotund parcel
#

Where is the data? a file named names.json?

steep compass
#

Yes

#

I would use sql but it's just so small I thought it's not needed...

#

But maybe that's the problem

rotund parcel
#

You are probably corrupting the file when multiple people try to read and write to the file

#

Yes you should use Flask SQLAlchemy

rotund parcel
#

super duper simple to use for your case

#

that tutorial is basically exactly what you need

steep compass
#

I used flask_limiter to set a limit of request per hour/day

#

Oh

#

Okay I'll look into that

rotund parcel
#

If you read from the file, then write to it, but another request is doing the same, it will corrupt the file.

#

Alternatively, you could use a simple threading.Lock() so that only one thread will ever be reading or writing to the file at a time

steep compass
#

That's probably the problem... Nice idea about the threading

#

I'll investigate

#

Thank you

buoyant shuttle
#

hey anyone here

rotund parcel
#

yes

buoyant shuttle
#
django.db.utils.IntegrityError: NOT NULL constraint failed: spotify_spotifytoken.expires_in``` i got this error, from using spotify API expiry in
#

its ia datetime object, doesnt seem to save in my field

rotund parcel
#

expires_in is Null. You need it to not be Null.

dry herald
#

How does developing on WSL2 with Docker compare to dual booting ubuntu?

rotund parcel
buoyant shuttle
#

ok

rotund parcel
#

Do people use WSL for Docker?

rotund parcel
dry herald
buoyant shuttle
#

also btw does textfiled take any mandatory afyments like max_length

quick cargo
#

but if your on a fresh install it's probably worth using the wsl backend

quick cargo
rotund parcel
#

Docker is great. Just wish it didn't use so much hard drive space

wicked elbow
rotund parcel
#

I'm currently using 24 GB of RAM

wicked elbow
#

yea, i need more ram. my 16gb of ram isnt enough these days for web development. seems insane. looking at getting another 16gb

rotund parcel
#

I built this rig back in Nov and I'm glad I went for 32 GB instead of 16 that everyone was recommending

wicked elbow
#

installing docker put me over the limit with pycharm and webstorm running at he same time. it doesnt help i always have 6 tabs open in chrome too. plus django server, npm and postgres server. just to much going on i guess.

rotund parcel
#

I have all that + multiple VirtualBox VMs going

#

RAM is cheap now. Well worth it to get 32 GB

#

especially for developers

wicked elbow
#

i have 4 slots, might as well use them. but 16gb has always worked for me. lmao. get another 16gb for like 80$ so might as well

rotund parcel
#

Docker is so nice though. No more needing to figure out why something works on my PC but not anywhere else

wicked elbow
#

man web dev blows. coding simultaneously in 2 different langues, python and js at the same time hurts my head switching back and forth between how to do stuff lmao since nothing is similar at all

tiny snow
#

ye async stuff throws me off

rotund parcel
#

Might be why lots of people use Node.js.

wicked elbow
#

lmao i would argue that being a full stack dev is a dying profession. most people dont want to do both

rotund parcel
#

I'm enjoying both. I don't like designing frontends though. They change too much

carmine swift
#

yeah i had to learn both and its kinda fun knowing both sides

wicked elbow
#

im not a ui/ux designer. if my app takes off, they are the first person im hiring

carmine swift
#

one man army for the most part glasses

wicked elbow
#

being a jack of all trades makes you an ace of none though

carmine swift
#

not when the job you have makes everyone be a full stack icri

#

stressful tbh lmfao

wicked elbow
#

lmao ya. cause it makes all errors your fault and you have to figure out if it was front end or backend that caused the problem. thats what sucks more then anything

#

god i hate websockets. it doesnt give you errors when something goes wrong

maiden tusk
# carmine swift one man army for the most part <:glasses:698599152845586453>

As a one man army what are the things you've found most useful to learn? I'm the only programmer I know and I feel like I've learned a tonne - Python, then Django, bootstrap, Wagtail, Linux and docker and I still feel like I know next to nothing 🙄
What do you guys think are the most beneficial areas to spend time learning to progress in web development?

carmine swift
#

I got to learn plenty from the questions I asked myself. But you know what they say. The more you learn the more you realize how much you dont know

wicked elbow
carmine swift
#

even though I have a job in programming the team im a part of follows the agile methodology

#

we have to be able to adapt to changes at an instant

#

sometimes overnight

wicked elbow
#

and thats to say that you find a job with python as the backend

#

wooh!!! i finally got my messaging app, and my notifications app fully real time pushing through a websocket. this has been a massive project thats almost done!!

carmine swift
#

most useful thing I learned is learning how to model your data

maiden tusk
#

I'm in a small team working on literacy in an undocumented minority language. I do a lot of scripty things but gravitated towards server and web stuff as a way to get non techy people using the tools I made. I'm a hobbiest, but I'm working on Python as my back up career if I ever need a career change.

#

I can see how learning to think about data in models would be really handy

native tide
#
return redirect('/test/<security_code>')
#

why wouldnt something like this work

#
from flask import Flask, redirect
import datetime as dt
import hashlib
import random
app = Flask(__name__)



@app.route('/')
def home():
    security_code = random.randint(10000000,99999999)
    f= open('logins.txt', 'a')
    f.write(str(security_code))
    return redirect('/test/<security_code>')


@app.route('/test/<security_code>')
def test(security_code):
    srrit = str(security_code)
    f = open("logins.txt", "r")
    for item in f.read().split("\n"):
        if strit in item:
            return "ur in"
        else:
            return "bad code lmao"

app.run()
#

this is my full code

wooden ruin
fervent vortex
#

can someone help with html

#

i used file dirs for img sources but it only shows a broken image

opaque rivet
# native tide ```py return redirect('/test/<security_code>') ```

your @app.route('/test/<security_code>') means that security_code is a query parameter.

When you do:
return redirect('/test/<security_code>')

You are not passing an int (security_code = random.randint(10000000,99999999) to your view. Your security_code will equal "<security_code>"

So do:
return redirect(f'/test/{security_code}')
to pass it to your view.

opaque rivet
small linden
#

hi, im doing some web scraping and sometimes the information i need is scraped and sometimes it is missing resulting in an error, any help?

fervent vortex
#

<img src="/images/mc_others_2.png" alt="...">

#

not too much for the image code

wicked elbow
opaque rivet
fervent vortex
#

the image folder is in the folder the html files are in

opaque rivet
fervent vortex
#

no

#

only html

opaque rivet
wicked elbow
fervent vortex
#

ok

#

it still doesn't wor

#

k

#

@opaque rivet

wicked elbow
#

for instance for what im doing, i have a 200 line consumer file to do just get response. everything else is handled directly though http like normal.

fervent vortex
#

wait nvm

#

i think it works

#

i also need help with bootstrap

#

the bootstrap somehow makes my nav bar go down

opaque rivet
fervent vortex
#

from doing this

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

wicked elbow
opaque rivet
#

linking it up with my dashboard for real time notifications too, so I thought websockets were needed

wicked elbow
#

well 1v1 with limited use other then for a short time you could do something called long polling. or a Hanging GET request. it has a timeout on it. if it expires it responds with expiration and the client sends a new request. depends on your notifications as well, if you have a bunch of notifications coming in at once consistently a websocket would work better. you can always do it for training. nothing wrong with that, but theres other methods you can use as well

#

could also use SSE, if your just looking for server events.

wicked elbow
safe solar
#
from flask import Flask, g
from sqlite3 import connect

app = Flask(__name__)


def get_db():
    db = getattr(g, "_database", connect(":memory:"))
    g._database = db
    return db


@app.teardown_appcontext
def teardown(exception):
    getattr(g, "_database", connect(":memory:")).close()


@app.route("/", methods=["GET"])
def root():
    db1 = get_db()
    # VS
    db2 = connect(":memory:")
    # do stuff
    db2.close()
    return "What is the point of access a db with db1, vs db2

The question is the return...

#

Yes I realize I did some dirty creates/connects... Just to keep it short.... on here.

#

If the app context is created when the request comes in, and always torn down when the requests is complete... Seems like doing it in function, is almost just as good. (No built in context manager, for connect, where as the other will always close the DB.)

stiff ferry
#

so what's the best way to visualize data inside the django admin?

carmine swift
#

what do you mean?

#

data from your database?

#

on the django web page?

glad patrol
#

hi

#

is there any libarary in flask to seprate user login

#

for example in my case i have patient login and doctor login but i have 1 login page for both

#

how i differentiate between both of them when doctor and patient enter their login credentials when doctor login the he redirect to doctor page when patient login he redirect to patient page.

carmine swift
#

look into permissions or i believe on flask its roles

wild echo
#

Hey

#

can someone help me with OAuth in flask?

#

and I have this code

    code = request.args.get('code')
    with open('config.json','r') as json_file:
        jsoncontent = json_file.read().replace('\n','').replace(' ','')
        client_id = json.loads(jsoncontent).get("client_id")
        client_secret = json.loads(jsoncontent).get("client_secret")
        print(client_id,client_secret)
    data = {
    "grant_type":"authorization_code",
    "client_id":client_id,
    "client_secret":client_secret,
    "redirect_uri":f"{request.base_url}".replace('/',r'%2F'),
    "code":code
    }
    encoded = base64.urlsafe_b64encode((f"{client_id}:{client_secret}").encode()).decode()
    headers = {"Content-Type" : 'application/x-www-form-urlencoded', "Authorization" : f"Basic {encoded}"} 
    post = requests.post("https://auth-dev.vatsim.net/oauth/token", data=data, headers=headers)
    response = json.loads(post.text)
    print(response)
    auth_head = {"Authorization": f"Bearer {response['access_token']}","Accept":"application/json"}
    user_details = requests.get("https://auth-dev.vatsim.net/api/user",data=data)
    session["user"] = user_details
    session["loggedin"]=="true"
    return redirect(url_for("index"))```
#

However, it doesn't work, i get returned invalid client type when I post to /oauth/token

#

{'error': 'invalid_client', 'error_description': 'Client authentication failed', 'message': 'Client authentication failed'}
This is precisely the error I get from the server

#

Can someone help identify the error in my code please?

native tide
#

anyone have any references to websockets and their thingies behind them?

stiff ferry
#

i found about ajax and flexmonster
which one do u suggest or is there a better alternative?

wicked elbow
#

anyone ever setup nginx with uvicorn/gunicorn?

nimble epoch
wicked elbow
# nimble epoch for django?

yea, need asgi access. debating on setting up a docker container for the whole set up. really dont want to do it all again

nimble epoch
#

oh so i think i cant help with it thought its an eazy setup

wicked elbow
#

i dont think its much different. django handles the wsgi/asgi stuff from the settings file im assuming. not sure how the server would fully know

nimble epoch
#

you can also publish it using heroku

#

if i got you right

#

also never used docker

valid girder
wicked elbow
nimble epoch
#

wanted to use aws till i found out its not free

wicked elbow
#

im on the 3.50 a month linux server plan

nimble epoch
#

oh probably a lot here can help you

wicked elbow
#

honestly super cheap for full fledged production testing set up

#

that guy going off about python has clearly never programmed... lmao python is easy compared to say js. that dev is garbage in comparison

#

man i got my chat real time, its actually super cool to send a message from one browser and see it show up on both browsers at the same time,

nimble epoch
#

yes it is

wicked elbow
#

anyone know how to make text not selectable on a webpage. its annoying to accidently highlight the alert numbers on my menu button

nimble epoch
#

try these: div { -webkit-user-select: none; /* Safari */ -ms-user-select: none; /* IE 10 and IE 11 */ user-select: none; /* Standard syntax */ }

wicked elbow
#

haha you must have found the same page i did. lmao thanks

nimble epoch
#

yes😆

#

just search it on google

wicked elbow
#

gonna have to cancel it for messaging and comments. nothing wrong with copy pastes working there

nimble epoch
#

you mean inputs?

wicked elbow
#

no to copy and paste someone elses message or comment

nimble epoch
#

so dont add it to those sections

wicked elbow
#

i did it for all divs, so gonna have to add a selectable class to undo it. seemed easier to add to everything then it was to add it in individual items. theres a ton of items. i stack divs 10+ deep in some places in the site. anyone ever scrapes it is gonna enjoy filtering out what they want lmao

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @snow hill until 2021-03-08 08:44 (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @inland copper until 2021-03-08 09:51 (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

quiet solstice
#

!unmute @inland copper

lavish prismBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @inland copper.

rocky knot
#

hi guys, any idea why my video tag is able to preload the video file in a static HTML file, but not able to do it through WebComponent?

#

on Mobile Safari on iOS

#

please @ me if you got anything

glad patrol
#

hi i am trying to genreate a random nubmber everytime patient register

#
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, DateField, PasswordField, SubmitField, BooleanField, DateTimeField, widgets
from wtforms.validators import DataRequired, Length, Email, EqualTo
from random import seed
from random import randint


class pateint_registraion(FlaskForm):
    patient_name = StringField ('PatientName', validators=[DataRequired(), Length(min=2,max=10)])
    dateofbirth = DateField('Your Date of Birth', validators=[DataRequired()], format='%Y-%m-%d')
    email = StringField('Email', validators=[DataRequired(), Email(), Length(min=2,max=50)])
    password = PasswordField('Password', validators=[DataRequired()])
    confirm_password =  PasswordField('Confirm password' , validators=[DataRequired() , EqualTo('password')])
    mrn = randint(1000,9000)
    submit = SubmitField('Sign Up')```
#

i use this mrn = randint(1000,9000)

#
@app.route('/pregistration', methods=["GET", "POST"])
def pregistration():
    form = pateint_registraion()
    if form.validate_on_submit():
        flash(f'Your account is created with name {form.patient_name.data}! your MRN is {form.mrn}','success')
        return redirect (url_for('plogin'))
    return render_template("patientregistraion.html", form=form, title="Patient Registration")```
#

but everytime i click on submit button it display the same number

opaque rivet
glad patrol
#

@opaque rivet pls tell me how I achive this.

rancid crescent
#

Can anyone help me with a django problem ?

nimble epoch
native tide
#

hello!:)

silk portal
toxic flame
#

the logical answer is no repl isnt a framework or language, it's just to temporarily host your website for testing purposes

spare iris
#

You can actually make a website w repl.it

#

I did it in middle school

opaque rivet
glad patrol
#

But I have to store this mrn in database as well for each patient

nimble epoch
#

if you want to give each user a mrn give your database a mrn field then after a user been created beside that create an mrn for it then show it whenever you want to

glad patrol
#

@opaque rivet I have 1 more question I have patient login and doctor login but I only 1 page for login how I diffrnentate between login if patient login he move to patient page if doctor login he will move to doctor page

opaque rivet
glad patrol
#

@nimble epoch it's not field it's a id which is auto generate when patient sign up

nimble epoch
#

just store it beside you user model

glad patrol
#

@opaque rivet can you share link pls

nimble epoch
#

create a new model and add a relationship

glad patrol
#

Oh

#

So I have to create relationship between patient and doctor as well because 1 doctor has multiple pateints?

opaque rivet
#

yep

glad patrol
#

Can you pls what this relationship is I mean how we achive this with simple model

opaque rivet
#

search it up, look at some guides. it'll be a one-to-many relationship, I don't use flask

glad patrol
#

@nicky pls share authentication link

opaque rivet
#

just search for a guide...

grim helm
#

a lil help with django dashboard, so i wanted custom auth and session maintenance and so i did something like

AUTHENTICATION_BACKENDS = ["discordlogin.auth.DiscordAuthBackend"]
and added custom models (all following a youtube tutorial)

now the admin panel isn't working cause apparently the user model of the default backend needs is_active as an attribute, what are the other attributes would i need?

'DiscordUser' object has no attribute 'is_active'``` 

<https://docs.djangoproject.com/en/3.1/topics/auth/customizing/>  doesn't give out any constriants to the user model 🤔
opaque rivet
grim helm
#

db.models.Model

#

something like

from django.db import models
from .managers import DiscordAuthManager


class DiscordUser(models.Model):
    objects = DiscordAuthManager()
    id = models.BigIntegerField(primary_key=True)
    discord_tag = models.CharField(max_length=80)
    avatar = models.CharField(max_length=100)
    public_flags = models.IntegerField()
    flags = models.IntegerField()
    locale = models.CharField(max_length=100)
    mfa_enabled = models.BooleanField()
    last_login = models.DateTimeField(null=True)

    def is_authenticated(self, request):
        return True
opaque rivet
#

hmm, from the error I'd just change it to:
class DiscordUser(AbstractUser)
(import AbstractUser, wherever it's found)

This way your model will inherit all of Django's User methods such as is_active.

grim helm
#

ah.. so the difference between a simple db.model and user.model is the other user methods and attrs?

opaque rivet
#

yeah, AbstractUser gives your model Django's User methods and fields, allowing you to also add your own, while AbstractBaseUser does not give you all of the methods / fields.

#

so by using AbstractUser you can have access to is_active, is_authenticated, etc.

grim helm
#

soo, when's a db.model used?

#

forms and stuff?

opaque rivet
#

well, whenever you don't need django's User methods. anything auth-related should extend the User model.

grim helm
#

aaaand, i cant make migrations , if i change to AbstractUser

auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'DiscordUser.groups'.
        HINT: Add or change a related_name argument to the definition for 'User.groups' or 'DiscordUser.groups'.
auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'DiscordUser.user_permissions'.
        HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'DiscordUser.user_permissions'.
discordlogin.DiscordUser.groups: (fields.E304) Reverse accessor for 'DiscordUser.groups' clashes with reverse accessor for 'User.groups'.
        HINT: Add or change a related_name argument to the definition for 'DiscordUser.groups' or 'User.groups'.
discordlogin.DiscordUser.user_permissions: (fields.E304) Reverse accessor for 'DiscordUser.user_permissions' clashes with reverse accessor for 'User.user_permissions'.
        HINT: Add or change a related_name argument to the definition for 'DiscordUser.user_permissions' or 'User.user_permissions'.
opaque rivet
#

mostly for business logic / products, stuff like that

grim helm
#

i see

opaque rivet
#

also, you need to go into settings.py and change your default auth model, as by default it is User

#

AUTH_USER_MODEL = 'api.Customer'

grim helm
#

ohhh

#

rit thx

#

okie no, i can't have a pasword field, cause the discordlogin thing just uses oauth2

You are trying to add a non-nullable field 'password' to discorduser without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option:
#

isnt it possible to use like something else for authing?

#

multiple things, discordUser being separated from the superuser admin login thing?

opaque rivet
#

you could change your User model, maybe remove the password field or set it to null=True, never tried it, but it could work

grim helm
#

after the make migrations?

opaque rivet
#

no, before the migration

grim helm
#

i dont have a password field in my discord usermodel, its inherited from the abstract model

opaque rivet
#

yes, it's extending django's User model, you'll have to edit it directly

grim helm
#

ah override it to null?

opaque rivet
#

yeah pretty much, so if the User model is found in django.contrib.auth... you navigate the source code until you find the model, then edit it

#

theoretically

grim helm
#

👍 ..

carmine swift
#

both are quick and easy to get set up and running

#

at our workplace we use powerbi for things like automated emails on queries we write. has visuals just like chartjs

native tide
#

im not sure where to ask this but i have a flask server running on a hetzner server how do i make it not local host?

wooden ruin
#

if you're using django, you can configure simple routing for static files, and simply return that image when you visit the url

lime mist
#
@sio.event
async def getText(sid, data):
    await processTextifyResuest(sio=sio, sid=sid, data=data)
``` ```python
async def processTextifyResuest(sio, sid, data):
    print(f"[REQUEST RECEIVED] {sid}")

    with ProcessPoolExecutor(max_workers=1) as executor:
        future = executor.submit(getTextFromBase64, data)
        text = future.result()

        print(f"[PROCESSED] {sid}")

        await sio.emit("text", text, to=sid)
``` Is this the proper way to implement Process Pool on a ASGI socket-io server that is trying to do OCR on given images? The goal is to handle multiple clients trying to do OCR at the same time
#
[CONNECTED] Vm-wy1fuUprw6FGkAAAP
[DISCONNECTED] Gt8t7kQyR9KHe_V-AAAL
[DISCONNECTED] UXsJ9POEQKZnRD74AAAN
[DISCONNECTED] Vm-wy1fuUprw6FGkAAAP
``` also the server keeps dropping all connected clients when they try to get an OCR at the same time
quick cargo
#

well that looks like because you block the thread while waiting for the process to finish

lime mist
#

how to implement it properly then @quick cargo

quick cargo
#

use run_in_executor because this is in a async context

stuck glen
#

html?

lime mist
#
async def processTextifyResuest(sio, sid, data):
    loop = asyncio.get_running_loop()

    print(f"[REQUEST RECEIVED] {sid}")

    with ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(pool, getTextFromBase64, data)

        print(f"[PROCESSED] {sid}")

        await sio.emit("text", result, to=sid)
``` @quick cargo so I implemented it like so and still it seems to drop clients when all of them make reqs at the same time
quick cargo
#

only when all of them make a request concurrently?

lime mist
#

I have 3 browsers open rn and I'm making req from one at a time as fast as i can so not really concurrently

#
[REQUEST RECEIVED] ies_gpxbsR64z1hjAAAL
[PROCESSED] ies_gpxbsR64z1hjAAAL
[REQUEST RECEIVED] NYgtkwlwlRstueXrAAAR
[PROCESSED] NYgtkwlwlRstueXrAAAR
[REQUEST RECEIVED] S58OHOu2sCx_7uhxAAAT
[PROCESSED] S58OHOu2sCx_7uhxAAAT
``` I don't think it's processing requests concurrently either, as you can see it's only accepting another req after solve
#
@sio.event
async def getText(sid, data):
    await processTextifyRequest(sio=sio, sid=sid, data=data)
#

can it be because I'm first receiving the data and then running a function @quick cargo ? is there a way to open an sio event on a new thread?

quick cargo
#

that shouldnt cause it because it'll be sent out as a task

#

do you not get any sio errosr?

wanton ridge
#

can someone help me here?

lime mist
quick cargo
#

hmmm

lime mist
#

maybe the huge base64 string that server receives to process is causing it? idk

#
Error in opening handshake
Traceback (most recent call last):
  File "c:\users\maila\.virtualenvs\server-e4oj0gxd\lib\site-packages\websockets\server.py", line 130, in handler
    path = await self.handshake(
  File "c:\users\maila\.virtualenvs\server-e4oj0gxd\lib\site-packages\websockets\server.py", line 586, in handshake
    self.connection_open()
  File "c:\users\maila\.virtualenvs\server-e4oj0gxd\lib\site-packages\websockets\protocol.py", line 328, in connection_open
    assert self.state is State.CONNECTING
AssertionError
``` got a handshake error for all connected clients and they again connected automatically @quick cargo
quick cargo
#

seems they're not properly handshaking or you're getting some event misshandling

native tide
#

Can anyone know how to make membership system in flask

#

Please @quick cargo

wooden ruin
#

@native tide you can start by planning out your sql tables, finding out how to "accept" payment, and thinking of ways to determine when a membership is expired. that being said, your question is a bit vague - try experimenting yourself!

dreamy hollow
#

Hey, I looked at http://pythontutor.com/ and I am really amazed. I just want to know the backend tech stack and how is the code executing and giving the global variables etc.

pearl latch
#

Hey, just a generic question about DRF. When overriding methods (create, update, etc.), is it better practice to do it on the View or the Serializer?

neat shadow
#

Is there anyone who knows how to use wtform in flask with css ?

#

got issues with dynamic form and my css file

proper path
#

there is someone please that can help me to configure my rasberry pi as a web server with nginx and flask?
i watched a lot tutorials but no one was really helpful

forest phoenix
#

Hi there, I'm working on a project which uses a chrome extension as a UI and I've already written all the code for the back-end in Python - would it be possible to run a Python script on Chrome like you might run a JS script?

native tide
#

but it's very unconventional thing to do

#

and also i dont think you will be able to make random users accessing your website run that python script

#

unless you mandate them to install that same extension

#

browsers arent built for running code written in python and other general purpose languages

forest phoenix
#

well I'm basically making a chrome extension for which I've written the entire back-end in python already

#

@native tide

#

and I'm just wondering whether there are tools out there to execute python files from the js or html of my chrome ext

opaque rivet
native tide
#

of doing things

#

browsers arent meant to speak python

#

but rather HTML, CSS and JS

#

JS isnt a hard language

#

you can write the front-end in it

#

and communicate with python's back-end just fine

toxic flame
#

yep

#

python as an api

forest phoenix
rotund parcel
#

Flask is good for making Python backends. Or Django

forest phoenix
#

As in the whole site uses python?

rotund parcel
#

I think Django or some full CMS let you build the whole site basically in Python, but no, usually that is not the case. It's a jumble of Python, JS, and HTML.

distant trout
#

ariadne or graphene for graphql?

wicked elbow
wicked elbow
glad patrol
#

i am trying to generate the random number every time user register

def generate_mrn():
    return randint(1000,9000)

class pateint_registraion(FlaskForm):
    def __init__(self, mrn):
        self.mrn = generate_mrn()
    patient_name = StringField ('PatientName', validators=[DataRequired(), Length(min=2,max=10)])
    dateofbirth = DateField('Your Date of Birth', validators=[DataRequired()], format='%Y-%m-%d')
    email = StringField('Email', validators=[DataRequired(), Email(), Length(min=2,max=50)])
    password = PasswordField('Password', validators=[DataRequired()])
    confirm_password =  PasswordField('Confirm password' , validators=[DataRequired() , EqualTo('password')])
    submit = SubmitField('Sign Up')```
i create generate mrn function and then assign mrn = generate_mrn()
`flash(f'Your account is created with name {form.patient_name.data}! your MRN is {form.mrn}','success')`
then i display it on page
but it always showing the same random number
merry quarry
#

Any help here?

spare iris
#

What do you want to do with it?

merry quarry
#

Do you see the drop down menu?

#

I want to scrape the teams from that dropdown menu

#

From Arizona to Washington

glad patrol
#

i am working on flask i have 1 login page
and two type of user 1 patient and 1 doctor both have diffrent regisration pages
i want to use 1 login page for both how i diffrentate between them during login and redirect to their corrosponding pages

dire fractal
#

Assuming you store unique info, use that

#

Such as username

glad patrol
#

i have username

#

but how to diffrenatie on login

#

like on login i am using email and password

dire fractal
#

is email unique?

glad patrol
#

ya

dire fractal
#

unique between both patient and doctor

glad patrol
#

yes

#

unique

dire fractal
#

Then just check the email on login, find the account and if its patient, do patient stuff

glad patrol
#

so you mean i dont need to use any decorator for this

dire fractal
#

Shouldnt have to

#

On login just check the type of person associated with the email

glad patrol
#

so i have to query from both tables

wooden ruin
#

how can i use ImageField instead of URLField when making images? also, how would i be able for a user to "upload" their picture, send it to django, and save it, if i can only send JSON data?, lastly, what does get_absolute_url() do?

dire fractal
glad patrol
#

@dire fractal thank you

inland copper
#

@wooden ruin

#

KrishnaKanth1729#1045

wooden ruin
# inland copper <@!729696323615588382>

i'm trying to learn how to use ImageField and FileField, but i don't know what things like upload_to mean and how to actually save an object that has the field. also, I'm wondering how i would be able to submit this file through JSON by using fetch, for example. if i'm sending a POST requst via fetch and using JSON as the body content, how can i send a file/image if all JSON is is just text inside an object?

inland copper
#

okay i will explain about

#

the FileFIELD first

#

all the files in django are stored as static or media

#

following me so far?

#

@wooden ruin

wooden ruin
#

yep

inland copper
#

okay

#

great

wooden ruin
#

static files are files like javascript or css files right? that are served in html documents kinda things right?

inland copper
#

yes and any files like images too

#

static files are used in development process

#

that is the developer uses to build the website

wooden ruin
#

Right

inland copper
#

media refers to the one the users uploads and needs to be saved in backend. like profile pics etc

#

this is a website i made

#

this uses the conept of stati and medi

#

a

#

files