#web-development

2 messages ยท Page 160 of 1

quasi relic
#

I already sent it

thorn igloo
#

where

quasi relic
#

sec

lavish prismBOT
#

Hey @quasi relic!

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

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

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

https://paste.pythondiscord.com

thorn igloo
#

oh, you're using wtforms,

quasi relic
thorn igloo
#

i've tried to use it to upload, but i never got it to work

lavish prismBOT
#

Hey @quasi relic!

It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.

Feel free to ask in #community-meta if you think this is a mistake.

thorn igloo
#

paste the text, the bot will automatically remove it

quasi relic
#

it seems I cannot send here files yay, ye I tried it

#

the text

mint folio
#

Anyways what I was going to say was that make sure you have the enctype as multipart/form-data to post files through a form.

azure saddle
#

I am getting the error TypeError: unhashable type: 'dict' and this is my code:

@app.post("/novels")
def add_novel(novel_data: Novel):

    new_novel = {
        "title": novel_data.title,
        "author": novel_data.author,
        "synopsis": novel_data.synopsis,
        "accepted": novel_data.accepted,
    }

    novels_collection.insert_one({new_novel})
    return {"data": new_novel}

When i try to just novels_collection.insert_one({novel_data}) it gives me a similar error TypeError: unhashable type: 'Novel' (this is using fastapi and pymongo)

quasi relic
quick cargo
mint folio
azure saddle
quick cargo
#

well, its already a dict

#

if you want it to litterally have those keys and columns as is in the db

#

just give it the var

#

if you want it to be stored like:

{ 
  "novel": {
    # ... Stuff  
  }
}
``` then use the `{"novel": new_novel}`

otherwise

just `new_novel` will produce:

```py
{
  "title": stuff,
  # ... etc...
}```
toxic plaza
#

Hi,
I'm building a content aggregator app which will scrape the data from some websites and present those data (after doing some formatting) to the frontend. I'm looking for some suggestions , references on the python framework etc. to use.

azure saddle
native tide
#

What is the difference between Django socket.io and Django channels?

#

what to use when?

peak lava
#

is it possible to change the maximum characters required to enter for django.contrib.auth signup password (which is 8)?

tough snow
#

Hey there, I was hoping to get some clarfication. I have been working with Flask for a few months now, and think it is awesome. I love the factory design principle that can be used, and blueprints. Also super excited about Flask 2.0 and the nested blueprints that are now available. I have always created monlithic apllications, and only really got introduced to the concept of Microservices recently. But as I was working through the concept, I was not clear how Micoservices would really be a change from just using Blueprints. Are they pratically doing the same thing? Or there advantages to using various microservices with or without blueprints?

terse vapor
twin hamlet
#

@buoyant shuttle hey

lavish prismBOT
buoyant shuttle
#

Sup

twin hamlet
buoyant shuttle
#

!paste

lavish prismBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

buoyant shuttle
#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

buoyant shuttle
#

So we can see

twin hamlet
#

now check @buoyant shuttle

#

!code

buoyant shuttle
#

Link?

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

buoyant shuttle
#

Paste the code to both views and url

twin hamlet
#

@buoyant shuttle Are you able to see code now ?

buoyant shuttle
#

Yeah I'm on phone switching to laptop

#

What's the problem again

buoyant shuttle
#

why are u jsonifying, a 403 forbinned error

#

403 means u cant access it

sacred forge
#

Can I add def to <button> in flask ?

#
from flask import Flask, render_template_string

app = Flask(__name__)

def test():
    print("test")

@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template_string('''
    <button>click me</button> 
    ''')

if __name__ == '__main__':
    app.run(debug=True)
#

How I add function to Button ?

buoyant shuttle
#

403, literally status means u cant access the content in that url

#

the server is stopping u

#
The HTTP 403 is a HTTP status code meaning access to the requested resource is forbidden. The server understood the request, but will not fulfill it.
#

it means the server got your request, but would not give u the ideal content

elder echo
#

Hi guys, I'm kinda new to css

elder echo
#

I know the basics, but I was wondering when should I get into bootstrap??

buoyant shuttle
#

you can stry to add a script tag, and run your js there

buoyant shuttle
elder echo
#

Yeah, I'm having a hard time making the websites I kinda pictured in my head

#

and I tried bootstrap but I didn't understand the "container" classes and all that

buoyant shuttle
sacred forge
#

for this

elder echo
buoyant shuttle
buoyant shuttle
#

plain container

sacred forge
buoyant shuttle
#

i suggest u learn js,

native tide
#

Getting started with flask in pycharm. I'm pretty sure my server is still running in the background after closing pycharm but I can't find what I should kill in the windows task manager... Is this common? Also is there a name for the default "server" back end of flask?

thorn igloo
native tide
native tide
#

so yeah

buoyant shuttle
#

kill the process running on your server lol

thorn igloo
#

hmm, are you on windows?

native tide
#

killed all python apps so not sure what to kill next

buoyant shuttle
#

also never start server in pycharm use cmd/terminal

thorn igloo
#

if so it's probably a python process

native tide
#

Yep and most google answers are for linux...

buoyant shuttle
buoyant shuttle
#

it runs on port 5000

thorn igloo
buoyant shuttle
#

kill port 5000, and it stops the process running on that port

native tide
#

so in order to test run a flask project I should run it outside of pycharm? Doesn't pycharm know how to handle flask projects and close it?

buoyant shuttle
native tide
#

alright will keep it in mind ๐Ÿ™‚ that background server also explains why I couldn't see the changes when running the script....

buoyant shuttle
#

np

vagrant remnant
#

As someone who keeps trying to learn Javascript but my own biases against it keep getting in the way, and I already know Python pretty well, is there a recommend tech stack for web development that minimizes the amount of JS I have to write?

fair agate
#

Anyone on with experience integrating PostgreSQL using psycopg2 into base flask for an API? I have some questions regarding best practices for integration, I'm used to SQLAlchemy so I'm eager to try to find cleanliness/DRY shortcuts for the code rather than bloating

fair agate
#

Is there anything wrong with having one handler function and having a series of if statements for method eg if request.method == 'PUT': as an example?

mint folio
#

Yeah it can get bloated, and hard to read or maintain

#

Each route should be doing a specific thing to a resource.

#

For your database functions, you might want to have a data layer and this way if you ever do have to change the implementation its easier to do so, without affecting other parts of your code.

jade lark
fair agate
jade lark
# fair agate How best do I go about doing this? I'm in the midst of figuring it out but I'm n...

Create a crud.py file in the same package. There you can create simple functions to read, update, delete, etc. Also there is absolutely nothing wrong with using if statements to delegate a request based on request methods.

I would recommend not having all of your logic in a route though. If you find you're doing that a lot. Create a utils.py file in the same module and create the logic there. If you find you're repeating something a lot and need the utils used across blueprints, move it out of the "app".

tulip dock
#

Hey, should I go for django or flask for learning web dev & execute my own idea?

#

It seems as if django has more data, so it would be better to learn

austere relic
#

I've used aiohttp so far

#

but idk

jade lark
jade lark
jade lark
austere relic
#

yeah. I don't see the problem

jade lark
#

Why would you want to use it for a server?

cyan lotus
#

django doesn't look into the "templates" folder under my app

#

I've added my app in INSTALLED_APPS and APP_DIRS is set to True

austere relic
#

why wouldn't I?

jade lark
austere relic
#

nah

#

xd

jade lark
#

I mean you definitely do but to each their own

austere relic
#

for templates there's jinja

jade lark
#

But there also is not much out there based on. This includes packages, tutorials, probably even stuff on stackoverflow. If you run into a big problem you're probably on your own.

austere relic
#

hmmm, that's fair a point

#

you're right that has been a problem

jade lark
#

I would guess it would be.

#

If you need an async option there are actual frameworks out there.

austere relic
#

maybe i'll try more stuff
but like it so far
def a lot better than apache + cgi

quick cargo
#

Sip Seems to be some miss-conception of stuff

#

aiohttp is fine with it's inbuilt webserver

#

its production ready, e.g. it's the same standard of gunicorn, uvicorn, hypercorn etc...

jade lark
#

Sure, it's fine.

quick cargo
#

What you shouldnt do still though is expose it without a reverse proxy really

jade lark
#

There is downsides as I pointed out.

quick cargo
#

Aiohttp has a bunch of stuff

#

it's not exactly a under-supported library

#

being the largest and most used async http library around

#

I still recommend putting the server behind something like Nginx because it protects you from all sorts of nasty and also allows for things like HTTP/2 which can boost performance

jade lark
#

A reverse proxy does *not *boost performance in most cases. Using it though is highly recommended though due to the security benefits.

quick cargo
#

In Pythons world it can, although typically not many people will actually make use of the the extra wiggle room it gives

#

HTTP/2 from client to proxy does add significant benefit though in terms amount of connections the proxy can handle vs the amount of requests it can process

jade lark
#

That is very very unlikely even in Python. The important part is using something such as gunicorn or uvicorn

quick cargo
#

due to the single connection multi-plexing

jade lark
#

Right, but a reverse proxy can only handle so much traffic itself. For example, look at something such as Kestrel.

quick cargo
#

yeah, although that number will be significantly higher than anything you write bloblul

quick cargo
#

not really

#

Proxies are very simple setups in terms of CPU time

#

by the time you have to add your database logic etc...

fast charm
#

hi guys, im learnining django-rest and i need a bit of help

quick cargo
#

your application behind it will take considerably longer

jade lark
#

Uh yeah, that's an IO problem.

#

not related to a reverse proxy

quick cargo
#

Things like Nginx and Apache have also got decades of optimizations behind them shrug

jade lark
#

Yes, but that doesn't mean it makes your server faster.

quick cargo
#

In most cases the raw execution speed is faster

austere relic
#

Think that another reason for reverse proxy was that you can run many aiohtttp instances

quick cargo
#

you can do that anyway

#

all python webservers rely on the pre-forking web server model to function properly

jade lark
#

If you're going to be scaling horizontally absolutely it's needed. It should always be used.

#

But saying it's faster ๐Ÿคฆโ€โ™‚๏ธ

austere relic
#

well, that's what the docs said idk

jade lark
quick cargo
#

I mean the docs do say it

Just call aiohttp.web.run_app() function passing aiohttp.web.Application instance.

The method is very simple and could be the best solution in some trivial cases. But it does not utilize all CPU cores.

For running multiple aiohttp server instances use reverse proxies.

No idea why though

#

I imagine it's referring to the fact that it's process management will be better than anything you setup in all likely hood

jade lark
#

Instances could be related to being instances spread across servers.

#

Or it could be if you had two instances running on the same server performing different tasks.

quick cargo
#

Nah, context for this is referring to a process

jade lark
#

Then yes you would want a reverse proxy.

#

Right but that's not what nginx does...

quick cargo
#

Mostly from aiohttp's perspective it's referring to not being able to fully use the CPU

jade lark
#

You would use uvicorn if you wanted to create more instances of the application.

quick cargo
#

well, you'd use gunicorn because it has better process management

jade lark
#

With an async server?

quick cargo
#

Yes. If you read the uvicorn docs it recommends you use gunicorn with the uvicorn worker rather than uvicorn just by itself

jade lark
#

That's still using uvicorn though?

quick cargo
#

Its a uvicorn worker

#

Not uvicorn managing the processes or sockets though

jade lark
#

Bruh

quick cargo
#

shrug Im talking in terms of the main controller not the workers

jade lark
jade lark
quick cargo
#

Well generally, its lightweight and has reasonable performance / good performance in comparison to the others, Eco system tools are also reasonably solid, most ASGI setups are compatible with aiohttp anyway.

The single process server is also possible the nicest thing in the world to deal with when deploying at scale vs dealing with blobs of gunicorn instances

#

blobpain Makes me wish there were more servers that supported a no-watcher process mode

fast charm
#

im getting this error when creating a superuser from a custom model user
TypeError: create_user() missing 3 required positional arguments: 'rut', 'first_name', and 'last_name'

and now im trying to find something so the superuser just require email and password, can it be done? or do i need to make another usermodel or something

jade lark
#

Do you have a user manager or an object manager?

fast charm
#

yes (im following a guide)

        """
        Create and save a SuperUser with the given email and password.
        """
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError(_('Superuser must have is_staff=True.'))
        if extra_fields.get('is_superuser') is not True:
            raise ValueError(_('Superuser must have is_superuser=True.'))
        return self.create_user(email, password, **extra_fields)
jade lark
quick cargo
jade lark
quick cargo
#

not in the ASGI world

#

like i said

#

aiohttp is the biggest async http libary in python

jade lark
#

For the request aspect, yes I can understand that it doesn't. (Does have a decent sized community)

#

but I have not yet seen or heard of anyone using it in production for a server

quick cargo
#

shrug People use, probably more than things like starlette or quart tbh

jade lark
jade lark
fast charm
#
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)

    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)
    email = models.EmailField(_('email address'), unique=True)
    user_type = models.CharField(max_length=20)
    rut = models.CharField(max_length=20)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

    def __str__(self):
        return self.email```
quick cargo
jade lark
fast charm
#

ok, then if i want to not use the fields can i make another custom user only for the superuser?

jade lark
jade lark
fast charm
#

yeah but that make the fields not required when making a user account right? in that case i should make them required on the frontend or smt

jade lark
#

You should be validating user input with a serializer though. You can specify that the field is required on there.

fast charm
#

okk, i didnt know that, im still making the models, serializers is that comes next thanks!

jade lark
#

No worries. You can also update the UserManager to require the fields. If you're new to drf you might have a bit of a harder time figuring out how to override the serializer.ModelSerializer if you're inheriting from it.

fast charm
#

oh yeah i got one method "create_user" that ask for values of the fields

jade lark
#

That's for all users

#

add the logic in the create_superuser function

fast charm
#

ohhhh right, because when i user manage.py createsuperuser i got the error, so if i update the create_superuser it should ask me for the fields when i createsuperuser (?)

jade lark
#

You'll have to test that one since it's been a while for me

#

You can always test if it exists in the extra field, or provide a default value for a extra_field

fast charm
#

ok i think i get it, thank you very much

jade lark
#

No problem! Best of luck

ember skiff
#

Does anyone know if there is a way to scrape fb data

austere relic
#

you'll need to know CSS and HTML though

ember skiff
austere relic
#

Make up your mind

ember skiff
#

Fb scraping sorry

#

Coz I tried with sessions and request

#

It says 505 error

austere relic
#

do you know html?

ember skiff
#

Yep

austere relic
#

hmmm okay

austere relic
#

with authentication

#

and the likes

#

So maybe use selenium instead

ember skiff
#

credentials = {"email":"your_email", "pass":"your_password"}
login_basic_url = 'https://mbasic.facebook.com/login'
def parse_html(url):
with requests.Session() as session:
post = session.post(login_basic_url, data=credentials)
parsed_html = session.get(url)
print(parsed_html)
return parsed_html

parse_html(url)

#

See this... I did this.... Gives 505 error

austere relic
#

sorry, I don't know how FB auth works

ember skiff
#

In the credentual part u just put in ur email n password

#

The authentication gets done

#

Also u need to explicitly male a url variable with the link to the post u wanna scrape

native tide
#

how do I do an external request in flask? etc:

headers = {
"rbx-authentication-ticket": csrftoken
}
requests.post('https://auth.roblox.com/v1/authentication-ticket/redeem, headers=headers)```
but within a flask  app.route endpoint
shy hatch
#

Hi, I'm using FastAPI and trying out Form rn, it forces you to provide a default value, but I don't want that, I just want it to return an error when the Form field is not found, is there a way for that? Or will I have to use Form(None) and check for NoneType myself?

#

Something like this:

@app.put("/user/new", response_class=ORJSONResponse, response_model=UserBase)
def user_new(username: str = Form(None), password: str = Form(None)):
   if not (username and password and len(username) > 2 and len(password) > 4):
        raise HTTPException(status.HTTP_400_BAD_REQUEST)
small arrow
#

this has to be a joke.

#

please don't do that ever running a web app with root is a massive security risk

#

any bug in the app will give users probably the access to the server with root privileges.
I know no one uses flask for publishing but I won't trust using this even at the localhost
since any testing and modifying to the database will maybe make your database files locked
with root only can edit to them.

wind dove
small arrow
#

Yes I agree. Flask is mainly used for web apps and doing that with knowing that it's for web apps can't be real.

tribal jay
#

Heyo, I'm trying to set up a Quart website along with an attached API at the /api endpoint. I've looked at the quart-openapi extension but I'm not sure if using the Pint from there means the entire website is works under the docs methods there and whatnot or if I can just designated a specific endpoint for it like with flask_restful. Not sure if I'm making sense, but any help would be much appreciated!
I'm wondering if I should just use normal Quart and make my own endpoints since it's just fetching data based on URL query args

median loom
#

sorry couldn't answer your question but do you know if django accepts new requests in parallel without having to resort to async?

tribal jay
#

No worries, never used django so can't help either ๐Ÿ˜ฆ

median loom
#

oh ok thanks anyway

#

hope your question gets answered

tribal jay
#

You as well ๐Ÿ™‚

elder echo
#

How can I make a multi page layout for my website?

#

I want it so when you click stuff in the navbar it prings you down

median loom
#

what do you mean pring?

#

if you want to link a url you can use <a href="link></a> or js

fallen marsh
median loom
#

oh

fallen marsh
#

Yea, use a link and add that inside a <div></div>

#

ezy

median loom
#

<div onclick="window.location.href = link;"></div>
could be used too

fallen spoke
#

Are Django rest framework applications vulnerable to XSS and SQL injection attacks?

cyan pine
#

Would i talk about selenium here?

inland oak
cyan pine
#

parallel execution of multiple tabs or windows with different links

inland oak
#

selenium is quite webby, so here is approriate too

cyan pine
#

well, im just trying to execute code on 12 different websites all at the same time

#

and i havnt found a thing on it

cyan pine
inland oak
#

I am trying to fit my API into having nice best practices REST logic

I have actions
customer register -> /customer [POST]
customer login -> what is it best url path for this? -> /customer/login [POST] -> perhaps this, since it created token for authentification
customer data -> ...? I would prefer having JSON payload, but GET request I think is not supporting it, I could fit into query parameter though -> /customer [GET]
customer update -> /customer [PUT]
customer send verify email -> API url: /customer/email [POST]
customer verify email -> API url: /customer/email [PUT]

#

well, probably above URLs will fit me better than what I did before

lime mist
#

how to encode a python dictionary into a URL variable? Example: {"id":"12345","first":16} => %7B%22id%22%3A%2212345%22%2C%22first%22%3A16%7d

native tide
# lime mist how to encode a python dictionary into a URL variable? ```Example: {"id":"12345"...
river nest
#

Hello

dusk portal
#

I'm facing issues at replication of urls.py means of app (include) in django
And i can't get docs can anyone tell me the way to get more output from docs I'm new at it and django doc's are soo much vast

desert estuary
#

what are the stuff i need to learn in networking so i can start with webdev backend and djangoo specifically

slim skiff
#

For dev you don't need much

#

you just need to point your browser at localhost on the port django is configured to use

odd terrace
#

One of my college tutors has said that when classes start up in September we're gonna be doing C# ASP for web backend because it's industry standard. I kinda don't wanna do that cos I already know Django.

Is it viable to go for a full stack career with Django as my backend system?

native tide
#

ะ•ัั‚ัŒ ั€ัƒััะบะธะต?

lime mist
#
urllib.parse.urlencode("VARIABLE")```
native tide
native tide
#

How do I send http response with image to client? Should I put the image bytes into the http response content like this?

HTTP/1.1 200 OK
Content-Type: image/png

{ Image data }
steel reef
#

can anyone provide me some resources for django restfull api

chrome reef
#

I'm getting a weird behavior. In the following code the first print is "True" but still the second print is never fired. Any ideas why?

#

response = json.loads(request.body)
print(response.get("newlikestatus"))
if response.get("newlikestatus") is True:
print("Is true")

native tide
nimble epoch
nimble epoch
native tide
nimble epoch
native tide
fossil comet
#

and you should never rely solely on a framework for security.

coarse haven
#

im vulnerable even when im used correctly ๐Ÿ˜ฅ

fossil comet
#

๐Ÿค”

modest scaffold
#

what is the modern equivalent of get_profile() in django

harsh summit
#

does anyone have any recommendations for css frameworks outside of bootstrap?

shy hatch
#

is there a way to set a form data field as mandatory in FastAPI? it forces me to set a default value, which is not what I want, i just want the request to fail if the form data field is not there.

autumn hedge
#

Anyone know the name of the artist?

proud quiver
#

I added the management command(basecommand). I give the file name as the command entry I added(I'm using is an Excel file). I want to open files with pandas and save line by line information to the model. I want to ask if I'm on the right track. Does it get the data properly? I'm going to send the excel file and source code. Can you help this topic?

#
from django.db import models
from django.utils.translation import gettext_lazy as _

# Create your models here.


class PaidDrugsUpdates(models.Model):

    class worksheet_type(models.IntegerChoices):
        ADDED = 0, _('Eklenenler')
        EDITED = 1, _('Dรผzenlenenler')
        EXTRACTED = 2, _('ร‡ฤฑkarฤฑlanlar')

    worksheet = models.IntegerField(choices=worksheet_type.choices)
    public_code = models.CharField("ฤฐlaรง Adฤฑ", max_length=6)
    barcode = models.CharField("Barkod", max_length=13)
    name = models.CharField("ฤฐlaรง Adฤฑ", max_length=250)
    old_barcode1 = models.CharField("Eski Barkod-1",max_length=13)
    old_barcode2 = models.CharField("Eski Barkod-2",max_length=13)
    e_code = models.CharField("EลŸdeฤŸer(Benzer) รœrรผn Grubu",max_length=5)
    reference_price_group = models.CharField("Referans Fiyat Grubu",max_length=7)
    list_entry_date = models.DateField("Listeye GiriลŸ Tarihi")
    activation_date = models.DateField("Aktiflenme Tarihi")
    passive_date = models.DateField("Pasiflenme Tarihi")
    generic_distribution = models.CharField("Orijinal/Jenerik/Yirmi Yฤฑl",max_length=12)
    high_sales_price = models.CharField("Depocuya SatฤฑลŸ Fiyatฤฑ 23,81 TL ve รผzeri ise",max_length=10)
    medium_sales_price = models.CharField("Depocuya SatฤฑลŸ Fiyatฤฑ 15,81 TL(dahil) ile 23,80 TL(dahil) arasฤฑnda ise",max_length=10)
    normal_sales_price = models.CharField("Depocuya SatฤฑลŸ Fiyatฤฑ 8,26 TL(dahil) ile 15,80 TL(dahil) arasฤฑnda ise",max_length=10)
    small_sales_price = models.CharField("Depocuya SatฤฑลŸ Fiyatฤฑ 8,25 TL ve altฤฑnda ise",max_length=10)
    special_discount = models.CharField("ร–zel ฤฐskonto",max_length=10)
    pharmacist_discount_rate = models.CharField("Eczacฤฑ ฤฐndirim Oranฤฑ",max_length=10)
    band_calculation_date = models.CharField("Band Hesabฤฑ Takibinin BaลŸlangฤฑรง Tarihi",max_length=10)
    distribution_document_date = models.DateField("Firma tarafฤฑndan DaฤŸฤฑtฤฑm Belgesinin BildirileceฤŸi Son Tarihi")

shy hatch
#

i thought those ... were something i had to fill in myself haha

native tide
#

I'm trying to format a date created by the django API

#
render() {
    const { blogList } = this.state;
    return (
      <context.Consumer>
        {({ a, getFormatDate }) => (
          <section className="blog-list">
            <h1>Blogs {this.state.a} </h1>
            {blogList.map((blog) => (
              <article className="blog" key={blog.id}>
                <h2>{blog.title}</h2>
                <hr />
                <div className="blog-body">{blog.body}</div>
                <p className="blog-author">{blog.author}</p>
                <span className="blog-date">{getFormatDate(blog.date)}</span>
              </article>
            ))}
          </section>
        )}
      </context.Consumer>
    );
  }```
#

In my component

#

this is the function I am using ```jsx
getFormatDate = (date) => {
console.log(date);
return new Intl.DateTimeFormat("en-GB", {
dateStyle: "full",
timeStyle: "short",
}).format(date);
};

#

But I get this error when the component is rendered.

#

RangeError: Invalid time value

#

this is an example of what kind of time values are passed to the function 2021-05-26T19:57:47.353005Z

austere relic
#

maybe like this?

new Intl.DateTimeFormat("en-GB", {
      dateStyle: "full",
      timeStyle: "short",
    }).format(new Date("2021-05-26T19:57:47.353005Z"))```
twin hamlet
#

Anyone know about django here ?

austere relic
#

bet. what's your question

steel reef
#

yep

plucky heron
#

who does graphql with the flask?

native tide
#
render() {
    const { blogList } = this.state;
    return (
      <context.Consumer>
        {({ a, getFormatDate }) => (
          <section className="blog-list">
            <h1>Blogs {a} </h1>
            {blogList.map((blog) => (
              <article className="blog" key={blog.id}>
                <h2>{blog.title}</h2>
                <hr />
                <div className="blog-body">{blog.body}</div>
                <p className="blog-author">{blog.author}</p>
                <span className="blog-date">{getFormatDate(blog.date)}</span>
              </article>
            ))}
          </section>
        )}
      </context.Consumer>
    );
  }```
#

So here in my render mehtod

#

in the article block in the p element I am rendering the author

#

the author is a user model in my django API

#

a customUser

twin hamlet
#

I want these checkboxes in front of the name like for e.g in front of NAME : Narayan Kohli

native tide
#

I want to render the name of the author and not the id

austere relic
native tide
shy hatch
#

are there any methods of getting the file size in bytes from FastAPI's UploadFile? or do we have to write the data to another temporary file and use that to determine file size?

ruby sorrel
#

hello there, hope everybody is having a good day.
new to programming. just started learning python a month ago.
trying to understand json files and accessing them through python
if i wanted to update a json file,

#

i was wondering if there was a way to append to it directly instead of having to re-write the whole file?

#
import json
# currently I understand that i first need to
# load the information on the json file as a variable
with open("test.json") as json_file:
    jf_var = json.load(json_file)
# and when i want to add information on to it,
# i add it the variable.
jf_var["feb"] = "february"
jf_var["mar"] = "march"
# but when i write it, to the json file,
# i feel like there is a more efficient way
# intsead of just re-writing the entire file
with open("test.json", "w") as json_file:
    json.dump(jf_var, json_file, indent=4)
# is there a way to just kind of append to the json file maybe?
outer apex
# ruby sorrel i was wondering if there was a way to append to it directly instead of having to...

https://stackoverflow.com/questions/12994442/how-to-append-data-to-a-json-file

json objects have a syntax that means the whole object must be read and parsed in order to understand any part of it
Hence there's no way to append data not already in a file. If this part is not taking up too much time, just stick with it. Otherwise there are a couple of other options you can look into for storing data!

ruby sorrel
#

i see. thank you

eternal briar
#

Has anyone worked with the Docusign api before? I am having issues with getting the auth to work ๐Ÿ˜ฅ

mental field
#

is it a good idea to reactify django?

twin hamlet
#

Anyone know about django here ?

native tide
austere relic
#

the way jinja inheritance works is something like this

<!DOCTYPE html>
<html lang="en">
<head>
    {% block head %} {% endblock %}
</head>
<body>
    {% block content %} {% endblock %}
</body>
</html>
{% extends "snippetAbove.html" %}
{% block head %} head {% endblock %}
{% block head %} content {% endblock %}

instead of this, is there a way to fill the blocks from one parent with multiple files?

<!DOCTYPE html>
<html lang="en">
<head>
    {% block from "head.txt" %} {% endblock %}
</head>
<body>
    {% block from "content.txt" %} {% endblock %}
</body>
</html>
austere relic
stable hemlock
#

I need help with async views in django. I get this error when I try to access my async view: ValueError: The view emailbot_dashboard.views.exclude didn't return an HttpResponse object. It returned an unawaited coroutine instead. You may need to add an 'await' into your view.

async def exclude(request): 
    try:
        guild = request.session['select_guild']
    except KeyError:
        return HttpResponseRedirect('guild')
    guild = 762450334513365002
    if guild:
        data = {"guild":guild[1]}
        
        excluded_channels = await get_excluded_channels(data)
        channel_names = [channel.channel_name for channel in excluded_channels]
        excluded_channel_form = ExcludedChannels(channel_names, True)
    return render(request,"Excluded.html", {"chosen_guild": guild[0], "form":excluded_channel_form})```
autumn hedge
#

@stable hemlock you need to add the async keyword into your route method

#

in flask its: but I could be wrong since i'm learning how to use async myself ๐Ÿ˜†

@app.route('/async/<something>')
async def my_async_request(something):
  my_async_response = await exclude(something)
  return my_async_response
chilly trail
#

which cms to use for django?

stable hemlock
opaque rivet
autumn hedge
#

Does anyone know which version of Flask is NOT multi-threaded?

median loom
autumn hedge
#

nevermind. app.run(port=8080, threaded=False) multithreading appears to be available since 0.12.5

stable hemlock
median loom
#

oh ok

#

that issue has been troubling me as well

peak lava
#
    form = UserCreationForm()
    if request.method == 'POST':
        regForm = UserCreationForm(request.POST)
        if regForm.is_valid():
            regForm.save()
            return redirect('login')
        else:
            for msg in form.error_messages:
             messages.error(request, f"{msg}: {form.error_messages[msg]}")
             print(msg) 
    return render(request, 'registration/register.html', {'form':form})```

so for some reason this line of code will always print me the following message on screen "password_mismatch: The two password fields didnโ€™t match.", even tho the passwords match but the problem could be for example, password hasnt met the min_lenght, it will still print the above message, any solutions to this?
outer apex
#

form.error_messages should be regForm.error_messages right?

peak lava
#

let me try that rq

#

yeap still the same thing happens

outer apex
#

Can you share UserCreationForm?

peak lava
#

how

outer apex
#

Oh I meant like copy and paste the code for that form on here? If it's too big a pastebin of it would be great.

peak lava
#

i dont have such code

#

its an import from django.contrib.auth.forms

outer apex
#

Ah I see. Can you share what you have in your template?

peak lava
#

this is what i could find on django docs of it

#
    """
    A form that creates a user, with no privileges, from the given username and
    password.
    """
    error_messages = {
        'password_mismatch': _("The two password fields didn't match."),
    }
    password1 = forms.CharField(label=_("Password"),
        widget=forms.PasswordInput)
    password2 = forms.CharField(label=_("Password confirmation"),
        widget=forms.PasswordInput,
        help_text=_("Enter the same password as above, for verification."))```
#

now that i look at it myself

#

i can see whats the problem

#

but how do i customize this

outer apex
#

What were you thinking of customizing?

peak lava
#

well

#

apparently

#

in this class only one type of error message is defined

#

and thats the one where password doesnt match with conf_password

#

my problem is

#

there is more errors that happen UI wise when it comes to registering

#

for example if i were to try entering password thats shorter than defined min_lenght for passwords

#

i want the error to be displayed as "Please enter a password that consists of 6 or more characters."

#

and not "'password_mismatch': _("The two password fields didn't match.")"

peak lava
# outer apex Ah I see. Can you share what you have in your template?

{% block content %}
{% load static %}

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Forum - SignUp</title>
    <link rel="stylesheet" href="{% static 'signup/style.css' %}">
</head>

<body>
    <div class="signin-box">
        <h1> Sign Up</h1>
        <form method="post" action="">
            {% csrf_token %}

            <div class="textbox">
                <input type="text" name="username" placeholder="Username" maxlength="10" autocapitalize="none"
                    autocomplete="username" autofocus="" required="" id="id_username">
            </div>
            <div class="textbox">
                <input type="password" name="password1" placeholder="Password" autocomplete="new-password" required=""
                    id="id_password1">
            </div>
            <div class="textbox">
                <input type="password" name="password2" placeholder="Confirm Password" autocomplete="new-password"
                    required="" id="id_password2">
            </div>
            {% if messages %}
            {% for message in messages %}
            <div class="help">
                <p><span style="font-size: 20px">&#9888;</span> {{message}}</p>
            </div>
            {% endfor %}
            {% endif %}
            <input class="btn" type="submit" style="opacity: 1 !important;" value="Sign Up">
        </form>


    </div>
</body>


{% endblock %}```
outer apex
peak lava
#

well not just pass leng

#

i also want to alert user when he tries to signup with a username that's already taken

peak lava
#

altho im rn really interested into finding out if it's possible to create an actual error messages that recognizes and alerts the user when he makes the error

native tide
#
from django.db import models
from django.contrib.auth.models import AbstractUser

# Create your models here.
class CustomUser(AbstractUser):
    
    def __str__(self):
        return self.username
    
class Blog(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    author = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    date = models.DateTimeField(auto_now_add=True)

class Comment(models.Model):
    author = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    body = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)

    class Meta:
        ordering = ['date']```
#

I have a CustomUser Blog and Comment

#

every Blog should be able to have multiple comments

#

When I go to the api in the blogs list in the author field it gives me the ID of the author. But I want the username and not the ID.

#

How do I fix this?

#

Same for the author fields in comments.

vestal hound
#

โ€œrepeat passwordโ€ dialogs are bad UX IMO

#

you should prefer revealable password inputs

#

you know, the kind which let you unhide what you typed

native tide
#

anyone can help me with this?

elder echo
#

How do I make it for my webpage to have different pages if you scroll down

#

like when you click the links it drags you down

jade lark
elder echo
#

Will it automatically go down even though I have a background image in my "body{ }" css?

#

I want a different background for that

autumn hedge
#

Alas. I figured out my Flask 2.0.1 issue around threading and refactored my little single thread app to now support multi threading. ๐Ÿฅณ

dusk portal
#

this line is of a django docs what it mean i cant get where i showed run .schema The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file and the database migrations shipped with the app (weโ€™ll cover those later). Youโ€™ll see a message for each migration it applies. If youโ€™re interested, run the command-line client for your database and type \dt (PostgreSQL), SHOW TABLES; (MariaDB, MySQL), .schema (SQLite), or SELECT TABLE_NAME FROM USER_TABLES; (Oracle) to display the tables Django created.

robust stone
#

Hey guys, how can i build a SaaS app ?

solar valve
#

is there any way to get duration between two string dates ?

median loom
solar valve
#

its is

#

i have a duration manager plugin for django which needs the feature

dense bolt
#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

floral nest
#

In python 3 app i am setting up a hello command and now it is setup successful but if i want to setup one more command in same file so how to. And i am writing down the second command then it is not working please help

peak lava
haughty shadow
#

hi
i am having trouble saving data to user account in django please can someone help

rustic wave
#

Many people in #846514617261621292 have created web apps that will coordinate with other people as to where the pixels will go... where do I start learning how to do something like this?

gritty cloud
#

well this is where the fun begins @rustic wave

#

i havent used the Pixels thing

#

it sounds cool

rustic wave
#

is cool*

gritty cloud
#

so the way this works (as far as i know)

#

you send a request to an api that pydis has

rustic wave
#

ya no i get how it works
but i dont get where do i get started learning to be able to do something like this

gritty cloud
#

first you need to pick a framework

#

i would use django

#

but flask would probably be better for this

#

next

#

send some requests

rustic wave
#

ive messed around me django and flask a tiny tiny bit...
django brianpoped me
flask made a bit more sense

gritty cloud
#

it is more effective for large and scaled projects

#

so next

#

make some requests

#

you can use the requests module

#

!pypi requests

lavish prismBOT
gritty cloud
#

@rustic wave

rustic wave
#

yup ik how to use requests

#

quite familar with it

gritty cloud
#

ok cool

#

so now we send requests to the api

#

idk what it is

#

probably has some docs to it

rustic wave
#

so any good resources to learn something like flask?

gritty cloud
#

tutorials on youtube

rustic wave
#

ya no ik how to interact with the pixels api.. my question was how to make something like pixels

#

ok ty!

gritty cloud
#

@rustic wave i found this playlist to be quite helpful while i was learning

#

How To Build Websites with Python and Flask! In this videos I'll walk you through building a very basic website with Flask. You'll see just how easy it is to get started with this powerful web framework!

Python is great, and building websites with Python is even better! Flask makes it super easy to build websites with Python quickly and eas...

โ–ถ Play video
#

it covers practically everything

rustic wave
#

ty!

gritty cloud
#

you want to make something like pixels?

rustic wave
#

ye

gritty cloud
#

and not just interface with it, but build it yourself?

rustic wave
#

ye

#

ik how to interface with it

gritty cloud
#

o wow this just got a lot harder

rustic wave
#

lmao

gritty cloud
#

so if ur building this

#

you really have no choice but to use django

#

it has the best database support

rustic wave
#

ah ok

gritty cloud
#

uh so you would probably need to learn it

rustic wave
gritty cloud
#

what is it?

#

@rustic wave

rustic wave
#

basically it will coordinate between multiple ppl

#

and tell them where each pixel will go

#

so liek basically a hivemind i guess

gritty cloud
#

uh i guess

#

but that rlly isn't neccesary

#

@rustic wave

#

we should let the people collab

#

and do whatever they want

#

we also would want mods on our db

#

to check for any criminal ... uh ... imagery

high raven
#

hello

sullen gust
#
database = SQLAlchemy()
DB_NAME = "database.db"

def create_app():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "YAEgysUiDlc1yNbe4MF10tMXaYqGbbo0"
    app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{DB_NAME}"
    database.init_app(app)

def create_database(app):
    if not path.exists("website/" + DB_NAME):
        database.create_all(app=app)
        print("Created Database!")

```Hello, so i have this and it stores my `database.db` in `/website` however i would like it so be stored in `/website/database`. can somebody please help.

`EDIT: solved the problem now!`
terse vapor
#

Can u add a token varible in html <a> tag? Like the token I have is jwt token?

hollow apex
#

Hey so

#

import requests
from bs4 import BeautifulSoup 


h = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
r = requests.get("https://www.worldometers.info/coronavirus/#countries") 
c = r.text
soup = BeautifulSoup(c,"html.parser")



main_table = soup.find("table", {"id":"main_table_countries_today"})
print(main_table.find_all('tr',{"class":"odd"}))



#

and this is the code

#

why would it return an empty list ?

#

cuz we see there are rows tagged with tr and class 'odd'

haughty gazelle
#

Hey why u block me

austere relic
hollow apex
#

I did it ,nvm

#

ty tho

austere relic
#

okay YuriSmile

#

_ _
I want to use this module to create certificates for my domain, but there's a few things I don't understand. Why does it end up with a .crt file? Thought certificates have the .pem extension?

#

also if anyone has a suggestion for a better way of creating certificates, then I'm open for that

native tide
#

ey is flask worthwhile?

magic sparrow
#

As always, it depends what you want to build

outer apex
# hollow apex why would it return an empty list ?

If you open that site on a browser, notice that there's a delay before the table gets populated? I assume that there's some JS that populates the table after it initially loads. You might want to inspect the HTML you get with requests and scrape using that instead of looking at what's on the browser.

From the initial load, it seems that there are already tables with data, but there are no classes associated with each tr elements.

native tide
astral pagoda
#

Would someone be willing to help me help chocolate. It is a question about imports and python files.

dense cloak
#

how do i get a pong message from aiohttp?

haughty shadow
#

hi can someone help me in django project

inland oak
haughty gazelle
native tide
#

TypeError at /search-posts/
as_view() takes 1 positional argument but 2 were given

#

class BlogSearchView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' def get_queryset(self): query = self.request.GET.get('q') return Post.objects.filter(title__icontains = query).order_by('-created_at')

#

path('search-posts/', views.BlogSearchView.as_view, name = "search-posts"),

#

the above is url

#

<form action="search-posts" method = 'get'> {% csrf_token %} <input type="text" name = 'q' placeholder="Search Post"> <button type="submit">Search</button> </form>

#

the above is form used to make it

#

Why am I getting that error how to solve it?

opaque rivet
#

@native tide .as_view is a method, so it should be called

steel reef
#

can anyone help me with django?

opaque rivet
#

Ask the question

steel reef
#

this my model for a loan

#

I want to change the date_given to datetime.now when the status is set to 'approved'

#

how to do this

odd terrace
#

you might be able to use signals

#

ive never used them but i looked into them a while back when i was first learning about models, from what i recall they can probably do what youre asking

steel reef
#

thanks a lot!, exactly what I was looking for, you really saved me a lot of time!

steel reef
buoyant shore
#

Hey i wanted to know why the _set command in django dosn't worl

#
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'User' object has no attribute 'Post_1'
>>>```
random lava
#

Hi, got a simple flask demo.
I render template with data=data

When i use {{ data }} in html it works

however in js, var data = {{ data }} doesn't work. How would i do it ?

median loom
#

the templating probably works only on the html file

random lava
median loom
#

wait, what should be defined?

random lava
#

if i used console.log({{data}}) for example

median loom
#

nope

#

the {{ }} formatting is processed at the server

#

before being passed unto the client

#

meaning the {{ }} tags are removed before it reaches the browser

stark tartan
#

Can we generate csrf token in view itself

#

In django

thorny nest
#

hey, does anyone know a better module than requests for webscraping

#

you can open urls with BeautifulSoup??

#

im sorry idk im new to this

stark tartan
austere relic
#

I don't understand the purpose of these records?

thorn igloo
# austere relic

you use them when you want a custom domain to point to your server

austere relic
thorn igloo
austere relic
thorn igloo
peak lava
#
                messages.error(request, form.error_messages["msg"])
                print(msg)```
any reasons why these lines of code in views.py upset my compiler so much? it displays "KeyError 'msg'" as an issue
```class UserCreationForm(forms.ModelForm):
    error_messages = {
        'password_mismatch': _('The two password fields didnโ€™t match.'),
        'password_short': _('Password is too short.')
    }```
this is the dictionary im trying to access and get values from
inland stirrup
#

its basically a record telling that go to this ip if you hit a particular domain name also the ns2.digit.........com is digital oceans library of sorts full of records that map/point you to an ip address or to a server

peak lava
#

nvm i've figured whats wrong

random lava
#

Hi, Whats the best way to do this.
I have my mainpage route and another route called data.

the data route redirects back to the mainpage but carries a param called data.
Im currently just using sessions but is there an easier way like redirect("/", data=data)?

manic mortar
#

ุฒูŠู†

native tide
#

Question.

#

Django related. If I want to update a propert of a object but the property is dynamically ?

#

How can I do that ?

#

*property

#

For prop in list:
Object.prop = value

vestal hound
native tide
#

I have fixed it right now.

vestal hound
native tide
vestal hound
native tide
#

Can you maybe explain your question

vestal hound
#

what is its type

native tide
#

Charfield

native tide
native tide
#

@native tide Hey, I saw your inquiry in the Flask Discord about securing an API. I too am working on an API in Flask, and I will likely run into the same issues you are. I'd love to see what you discover.

Additionally, I was going to recommend JWT, but I don't have much direct experience working with that in Flask.

inland oak
# austere relic

You are currently using your own name server. Ns records allow delegating this task to another provider, if I get it right

austere relic
#

yeah, but right now they are delegating to themselves??

inland oak
#

ยฏ_(ใƒ„)_/ยฏ

#

Few days ago I wondered the same
Still wondering

median loom
#

padding?

astral pagoda
#

Can someone help with python imports in #help-pie

median loom
#

yeah padding in css

vestal hound
#

you can look into flexbox

#

what exactly do you want to do?

vestal hound
# median loom oh ok

you can think of it this way: padding is between everything in the element and the border, and margin is between the element's border and the next element's border

median loom
#

oh ok thanks for the info

scenic turret
#

i am running into an error while trying to launch a django / socket.io project to heroku. Anyone have experience?

nova bane
#

is pyppeteer faster than selenium?

inland oak
#

and it is even fastest for demo web sites

nova bane
#

sry , i googled it and found pupeteer is faster but i wasnt sure about pyppeteer

inland oak
steep summit
#

hi'

short wave
#

someone know why when i try to load my html files i get this?

#

how its rn:

marsh canyon
#

can you show index.html

#

I would recommend separating your html from css and js

#

css, js and images come under static files

short wave
#

i did it from a html builder

marsh canyon
#

you need to handle static files in a diff way.

#

the link I sent above has all the details for it โ˜๏ธ

#

I would recommend you to also look into template inheritance

silver wraith
#

is there a way to know if a client have disconnected from Flask? like for example a user is no longer connected to the@App.route('/')

short wave
marsh canyon
#

nice ๐Ÿ˜„

limpid pivot
#

I have a website that I deployed in Heroku. It does scraping on the button click. But it takes a lot of time and in Heroku timeout occurs after 30 seconds. Now how can I make the script run in the background?
PS: I have used Selenium for scraping and web app is made in Django

Edit : After the script run it gives a download option to the user.

wide canyon
#

Hello. I'm having issues with django. My server isn't serving static files. It's on digital ocean and I'm using nginx and guniicorn. I'm not a Linux guy So I don't really know much about it. What files Do i need to share with you for you to help fix it? Please help. Thanks

wide canyon
scenic vapor
#

Hi quick question, whats best practice for api calls? single bulky calls or small targeted calls?
should i request for the whole inventory and send product info via props or call a single product on each product page?

random lava
#

Hi, is it possible to pass arguments through a redirect?
So like:

data=1
return redirect("/", data=data)

flask btw

inland oak
#

pagination is supported at API frameworks level usually

#

keeping somewhere hidden data, which you do not render, is usually a bad practice

autumn veldt
#

hi this is my main code : ```py
import requests
import uvicorn
import json

from fastapi import FastAPI

discord_token = "BotToken"

app = FastAPI()

@app.post('/discord-user')
async def discord_user(id):

user_id = id


headers = {'Authorization': f"Bot " + discord_token}

r = requests.get(f"https://discord.com/api/users/{user_id}", headers=headers)

data = r.json()
hash = data["avatar"]
data["avatar"] = f"https://cdn.discordapp.com/avatars/{user_id}/{hash}.png"
data["avatar_gif"] = f"https://cdn.discordapp.com/avatars/{user_id}/{hash}.gif"

return data

this is the test file:

```py
import requests

r = requests.post("http://127.0.0.1:8000/discord-user", headers={"id":"690099836963651695"})

print(r.json())
#

i get ```
{'detail': [{'loc': ['query', 'id'], 'msg': 'field required', 'type': 'value_error.missing'}]}

#

y ?

gray creek
#

I think you need to pass them into the data kwarg and not the headers kwarg

#

Try that out, @autumn veldt

#

i.e. requests.post('url', data={'id': whatever})

autumn veldt
#

ok

burnt night
#

I made a schedule keeper of sorts.
and I only have 1 more obstacle

#

When the time for the schedule arrives, I want it to send a notification...
but I have ZERO idea of how to do this background checking :(

#

Using Flask

scenic turret
solar valve
#

Can we have wagtail cms based on user ???

sharp tiger
#

Can I make static websites using python flask?

#
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def hello():
    message = "Hello, World"
    return render_template('index.html')
if __name__ == "__main__":
    app.run(debug=True)
silent owl
#

I'm building a django app where I want to run cron jobs based off data that currently exists in the database. Once the cron jobs are complete I want to send a put request back to my django server and update with the new date (or modify the db object with the ORM using a task script whatever is easier). I am looking at celery for this and seems like it is what I'm looking for but not totally sure. Anyone know if there's a better option? I haven't really worked with cron jobs/task runners and stuff before

inland oak
#

you will have total control at your code level about your tasks

opaque rivet
#

i don't really know anything about cron, which is why i ask

inland oak
# opaque rivet why is celery better than cron?

https://www.reddit.com/r/Python/comments/m2dg8/explain_like_im_five_why_or_why_not_would_celery/
read here different reasons

as for purely my reasons... cron lives outside of application. python at best can be only accessing its internal control.
while celery lives basically purely inside your code project and only uses Redis database as memory storage to work.
I prefer having things like that tightly packed into my code project

opaque rivet
#

yeah I guess if you deploy, having it all centralized in a .py file is easiest

#

surely celery uses cronjobs itself

silent owl
#

@inland oak cool thanks for confirming that for me. As long as I can perform actions on the DB and schedule tasks based on DateTime fields that's all I really need. Sounds like i should be able to do that fairly easily with it

wooden ruin
#

are you running trying to deploy via ASGI or WSGI?

short wave
#

someone know where i can learn more about alignment? i want try something, for example put this graph on the center of the page, try to put the graph on the left and one table with some infos on the right side of the graph...

wooden ruin
dapper solar
#

can anyone help me with google programmable search engine?

#

i am not able to do an image search

prisma canopy
#

Hi, I am creating a simple flask web blog application with bootstrap, When i click certain things of navbar, that shows not found and changes it's end points automatically, can anyone help with this please.

#

Hi, I am creating a simple flask web blog application with bootstrap, When i click certain things of navbar, that shows not found and changes it's end points automatically, can anyone help with this please. Plox help

#

what do you mean

scenic turret
fair agate
#

What is the best way to query an existing URL API via Flask application?

worthy lake
#

Whats wrong with margin-top?

#

Then put a container up there and leave it empty. And when they do the thing, select the element and put the thing in there.

#

So what you have is

<div class="global-container">
  <div class="container-for-new-thing"></div>
  <div class="container-for-buttons">
    <!-- the code you have above -->
  </div>
</div>
#

And when you create the element of the thing that you add with JS, you select that container for where to put it

#

Which is just an empty space already there.

#

you would probably use more appropriate classes

#

But that is why you see every element always is contained in a millions divs

native tide
#

How do ya think

distant trout
#

do you guys think threejs is too bloated?

#

wanna use it with my nextjs app but feel like it might bloat my site even more

fair agate
#

When I return a JSON object, how can I have the Response code after it

modest scaffold
#

is there a django method for validating whether a string meets the requirements for a username

hoary orchid
#

im working on a flask application and i faced a wierd problem when i uploaded to production all my apis now got /static/ before the actual api and that cause a problem that when i reload the web fall because there is no /static/ api why this happens and any idea how can i fix this?

modest scaffold
#

username_validator = RegexValidator(r'^[\w.@+-]+$',_('Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.'), 'invalid')

#
  File "<console>", line 1, in <module>
TypeError: 'str' object is not callable```
#

why error

#

where is the password validation code for django

serene matrix
#

Hello, I'm new to django and I have 2 problems I need help with.

Firstly,
I have a view that showx "You are logged in as [x]". After login is successful it shows "You are logged in as anonymous user". How do I fix that.

Secondly,

I have a remarks form on lower-level users. This allow highLevel users comment on lowLevel users. The form is supposed to take both the id of the logged in user and the Id of the user to be commented on and create a database entry associated with both users. How do I make the form collect both users Id (I used foreignkey to link the models)

THis is so long

scenic turret
#

i am getting an error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. when trying to deploy to heroku. Any idea?

silent owl
#

i always found that part of deploying to heroku to be a pain point

#

but im noob

#

obviously you wouldnt need to worry about local app directorys being included in that

#

i'd also look at your traceback to see at what package it is failing with

scenic turret
silent owl
#

not necessarily

#

copy paste both to me please

#

try committing to heroku again and see what the traceback says as well, it will show the specifc package it is having trouble with i think

rustic sky
#

Hi. Have a quick question about the use of webapps for certain stuff

#

Trying to create a website "hybird"(?) with django. Right now I'm on the part of creating a homepage... do I use the main app, or create another?

Watching a tutorial, and the person used the main app

#

already created another and I'm somewhat worried it wasn't necessary, because then I'll have to delete it somehow

vestal hound
rustic sky
#

yeah

#

err, project

vestal hound
#

huh?

#

app orp roject

#

they're two different things

rustic sky
#

I'm (still) very confused

#

but

#

err, app, yeah

#

two apps in my project... the main one, and then one I created that may not be necessary anymore

vestal hound
#

contains one or more apps

#

you can think of apps as plugins

#

that can be added/removed at will

#

to change the functionality of the project

rustic sky
#

yeah

vestal hound
#

in general

#

each app has its own sphere of responsibility

#

for example, say you're designing Instagram

#

you might have an insta_images app to handle image processing, insta_chat for chat, insta_store for the store, etc.

rustic sky
#

oh, yeah

#

okay, well....

#

either this person in a tutorial I'm seeing set it up somehow in the video or not... but he created a views.py and other things in what looks like his main app to create a homepage

#

do I do this... or should I keep the other app I created and put all the stuff there...?

vestal hound
#

on your planned architecture...?

#

I can't answer that question for you

#

but

#

it's probably not somtehing yu need to worry about rihgt now

rustic sky
#

honestly, I'm not sure now lol

vestal hound
#

stick to one app

#

if you're starting out

#

this is not something you need to care about

rustic sky
#

my big worry is deleting the extra one and breaking stuff

vestal hound
#

just leave it there

rustic sky
#

mmm ok

native tide
#

Hey how do you change the change password form in Django

stuck palm
#

Hi, I'm working with leaflet, Flask & sqlite3. I'd like to generate a layer on the map that covers the entire map apart from small circles where the user has been. How would be the best way to go about this? Would I need to have JS render images with circle cutouts or would it accept a huge multipoint geojson also?

#

The coordinates it would need to generate circles around are stored in the database

inland stirrup
#

i want to connect my html form so that it uses the rest api and uploads a file using some function in flask ..... how do i connect the html form and rest api??

ebon hemlock
#

any idea why the background and avatar images are not working on the server? how can i fix it ?

short crystal
#

@wispy dirge

wispy dirge
wispy dirge
wispy dirge
# wispy dirge

if request.POST['password1'] == request.POST['password2']:
user = User.objects.create_user(username = request.POST['username'],password = request.POST['password1'])
user.save()

#

**I have done with this method when I was learning python last week and It worked perfectly fine now I tried again its not working even both are same **

marsh canyon
#

can you just print request.POST

#

we could check if those fields are included

#

or if the forms were messed up

short wave
#

guys i have a form like the img
how i can make when someone click on the Search button he get the name input of the first area to go to a link like: link/input_name?
example: www.google.com/ab

marsh canyon
#

is the site static or using any framework?

short wave
#

its static i think . _.

marsh canyon
#

have you worked with js before?

short wave
#

never

#

i mean i did 9 years ago . _.

marsh canyon
#

you will need some js to make that happen ๐Ÿ˜„

#

the process would be to listen to the click event on the button and then read the content of the form input field

#

then redirecting the user

short wave
#

actually he use something like:

<form action="https://www.itemsearch.com" method="POST" class="u-clearfix u-form-custom-backend u-form-spacing-15 u-form-vertical u-inner-form" style="padding: 10px;" source="custom" name="itemsearch" redirect="true">
...
<div class="u-align-center u-form-group u-form-submit">
              <a href="#" class="u-border-0 u-btn u-btn-round u-btn-submit u-button-style u-custom-font u-font-lobster u-gradient u-none u-radius-50 u-text-black u-btn-1">Search<br>
              </a>
              <input type="submit" value="submit" class="u-form-control-hidden" required="required">
            </div>

i was thinking if i could just change the form action to have something like in python: form action="link/"+var_input

marsh canyon
#

not sure how that would be done tho

lusty arch
#

hi guys, have any of you used dash plotly with flask? I'm trying to secure it with flask security too but i don't know how to do it. thank for your time

slim beacon
#

Hello everyone! I am using Flask and SQLAlchemy. Is it possible to relocate the Flask routes and the model from the app.py file to their own respective file?
My app.py is awfully long and it would be easier to read if it is possible, but I can't seem to figure out how to do this!

inland stirrup
#

i don't really understand your question but your problem is really long app.py right?

of course you can
create functions in another file and use import at the beginning of app.py to be able to use them
so you just have to invoke the function in app.py

limpid pivot
#

I have a website that I deployed in Heroku. It does scraping on the button click. But it takes a lot of time and in Heroku timeout occurs after 30 seconds. Now how can I make the script run in the background?
PS: I have used Selenium for scraping and web app is made in Django

slim beacon
inland stirrup
slim beacon
#

Another peculiarity is that the routes module is imported at the bottom and not at the top of the script as it is always done. The bottom import is a workaround to circular imports, a common problem with Flask applications. You are going to see that the routes module needs to import the app variable defined in this script, so putting one of the reciprocal imports at the bottom avoids the error that results from the mutual references between these two files.

#

This is what I needed!

inland stirrup
slim beacon
#

that is from that link

#

it was a copy paste

#

also, it doesnt work lol

inland stirrup
tidal slate
#

Hi! I have some difficulties in implementation of validate() method for ModelSerializer.
So, there are some rules that check if data that is gonna be saved to db is valid.
The problem is that in case of update this should be checking against merged instance and validated_data
and for create I should perform checks for validated_data only

Using 2 different serializers feels not DRY to me.
Checking for self.instance and validated_data.get("field_name") is also kinda ugly, especially when it is partial_update

Is there some elegant approach to it?

low glen
#

please help , this is my cmd , i am trying to learn django

tidal slate
#

python manage.py migrate @low glen

low glen
#

i am trying to paste the server addresss , but it is not opening

#

how to do so

tidal slate
#

stop server
run migrate command
start server

low glen
#

this is coming

tidal slate
# low glen

enter this address in address bar, not in Google's search field

low glen
#

but now i had run migrate , will it be a problem now

tidal slate
#

it will be even better ๐Ÿ™‚

low glen
#

ok , let me see sir

#

thanks a lot

#

!close

fading gazelle
#

Hello I was doing programming with Mosh's Python course (https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=19732s) but There is a problem when making migrations in Django it is always telling No changes detected . But I tried everything They told but it is still not working . Anyone help me

Python tutorial - Python for beginners - Go from Zero to Hero with Python (includes machine learning & web development project).
๐Ÿ”ฅ Want to master Python? Get my Python mastery course: http://bit.ly/35BLHHP
๐Ÿ‘ Subscribe for more Python tutorials like this: https://goo.gl/6PYaGF

๐Ÿ‘‰ Watch the new edition: https://youtu.be/kqtD5dpn9C8

๐Ÿ“• Get my FREE ...

โ–ถ Play video
buoyant geode
#

ModuleNotFoundError: No module named 'flask._compat' i have already flask installed in my system but i get this error

#

some one help me pls

drifting crater
#

once you have made a model for your web app, then you register your app in INSTALLED_APPS and then you can run makemigrations and migrate

tight dust
#

hey guys one question
so I was planning to build a full stack app with MERN, but I want to integrate a recommender system(coded in py) with it. How do I send the data to my node.js backend actually?

#

is this the right approach or will it be better to move to a django/flask based stack?

calm plume
#

You can send it from Python to Node using your own API if you wish

fading gazelle
tight dust
drifting crater
scenic dove
#

Hello

#

I have a question about django can someone show me how to share the code here

digital hinge
#

You can use bpaste or type ` 3 times followed by py

opaque rivet
#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

drifting crater
peak lava
#

from which django library do you import "auth_login"?

#

nvm found it

arctic shard
#

I'm planning to make an image api
I will be using heroku as my host (I don't know where else I could host the api for free ofc since it's only a project)
But since heroku reverts back to its original form when the server restarts the images will be deleted so I need an online database Do you guys know any?

calm plume
#

Are you storing image links or files?

arctic shard
#

Files

calm plume
#

Ah, then no idea

arctic shard
#

Is Firebase a good one?

#

What about if I store the file as bytes

arctic shard
calm plume
#

Firebase, Mongo, Supabase, anything

arctic shard
dull pier
#

@arctic shard you may still use firebase. You just have to convert image to base64 (so it outputs as a string) and put it in firebase

#

links look dated, you may just do something on the same lines. Firebase API must have changed in 5 years

arctic shard
dull pier
#

I ain't selling you Firebase ๐Ÿ˜† just that if you have really trivial use cases then you could just use it simply

arctic shard
quick cargo
#

Err for images -> Probably not

#

also base64 encoding images generally leads to alot of bloat

#

an image api on a free Heroku instance is probably not the best idea

arctic shard
#

Just a project for testih and understanding APIs

#

also I shouldn't store images as base64 because it might will bad?

quick cargo
#

well there isnt anything wrong with base64

#

but it will increase the storage size

arctic shard
#

I thought it will be smaller since string

#

So using firebase as database is better than using sql database for images?

quick cargo
#

Err they're probably all equally bad

#

I mean you might only be storing a few images and serving a few images

#

in which case you might? get away with it

arctic shard
quick cargo
#

but any sort of load on any of these cloud databases or free tiers will probably blow through your allowance in no time

arctic shard
#

I don't have allowance lemon_angrysad

quick cargo
#

the allowance the free tier gives you

#

e.g. the amount of usage your allowed before it cuts you off

arctic shard
quick cargo
#

thats just storage

#

that doesnt include the bandwidth cap

#

If you want my advise: just store the images on heroku

arctic shard
#

What do people with proper hosting do with their images?

quick cargo
#

generally store them as static files or use a CDN setup

arctic shard
#

Cdn like

#

This right?

quick cargo
#

idk how discord has their setup but generally its something like a cloudstorage setup and served globally, or its stored in a managed database

#

But either way you blow through bandwidth rather quick with image serving

arctic shard
#

If they are generally stored...
The system copies the file and give it to the user?

quick cargo
#

pretty much

#

theirs alot more going on under the hood

quick cargo
arctic shard
#

I can't find any api reference for this stuff

quick cargo
#

their is a surprisingly low amount of info around this stuff.

#

mostly because no real good solutions exist ig

#

but the setup i linked to above is definitely not suited to low ram, low storage servers

arctic shard
quick cargo
#

Ig you can call it that?

#

In most cases it's probably just a bunch of static files being served by nginx

arctic shard
#

Tbh I'm trying to make a ||thigh|| api ๐Ÿ˜ณ And I kinda wanted it to be open source so static Posting the images in github might get me in trouble

quick cargo
#

Mm for end use I dont think it would be a good idea to try run it on a free server

obtuse kite
#

this is the error

#

image= models.ImageField(upload_to='uploads/', blank=True, null=True)
thumbnail= models.ImageField(upload_to='uploads/', blank=True, null=True)
date_added= models.DateTimeField(auto_now_add=True)

class Meta:

    ordering = ('-date_added',)

def __str__(self):
    return self.name

def get_absolute_url(self):
    return f'/{self.category.slug}/{self.slug}/'

def get_image(self):
    if self.image:
        return 'http://127.0.0.1:8000' + self.image.url
    return ''

def get_thumbnail(self):
    if self.thumbnail:
        return 'http://127.0.0.1:8000' + self.thumbnail.url
    else:
        if self.image:
            self.thumbnail = self.make_thumbnail(self.image)
            self.save()

            return 'http://127.0.0.1:8000' + self.thumbnail.url
        else:
            return ''

def make_thumbnail(self, image, size=(300, 200)):
    img = Image.open(image)
    img.convert('RGB')
    img.thumbnail(size)

    thumb_io = BytesIO()
    img.save(thumb_io, 'JPEG', quality=85)

    thumbnail = File(thumb_io, name=image.name)
#

(this is the code)

prisma canopy
#

I am making a flask website with use of bootstrap. When I click on options provided on nav bar, sometimes some options changes their end point to the file from which they are being rendered and give not found error๐Ÿ€pls help

#

@quick cargo can ya help please ๐Ÿ™

#

Ping when anyone is telling a solution going to sleep bye

mossy hamlet
#

Hello!
I have deployed a Flask application on a server but all routes return a 404. The central log of the server is unreachable for me due to the provider.. so I'm looking for ways to test or call routes from python side to try to see potential error messages.

This 404 on all routes is a big black box for me and I can't find the culprit line.

PS: App runs on my local, but the server deployment is using apache and wsgi.. hence the difference.

#

How can I find the error?

merry hearth
#

Its funny to discover an exploit to my own website

median loom
median loom
#

Hi I need help in django.
I've just started learning it and until now i've been using manage.py runserver <ip address:port> to run my django project. I've heard that it shouldn't be used for deployment, that it's just for testing if it works.
Any advice on deploying my django project to a server??

median loom
#

ohh so gunicorn is the standard

#

i see

#

thank you very much

inland oak
#

You will need handling static files differently

inland oak
#

Best practice to handle static files with nginx

median loom
#

ok noted

inland oak
#

In advance you need to apply manage.py command

#

Which gathers all your static files

#

In one folder

median loom
#

it's in the manage.py help right?

median loom
#

ok thanks

inland oak
#

It requires some settings changing

median loom
#

oh ok, it's the STATIC_ROOT right?

inland oak
#

Not remembering

median loom
#

ok thanks for your help

#

i can probably handle this already

inland oak
#

U a welcome

teal bane
#

hey guys i have a school project that consist to do an app of scanning network equipment's like switches and routers i did the python scripts in a traditional way but now i need to integrate my work in a web app but every thing is stuck i never used django before i even tried the simplest things to add a bootstrap page no success i dont know how use the scripts in this web app i feel so lost and time is ticking please any help

median loom
#

if you need something simple and quick, you should use flask instead of django

#

the directory structure is much simpler compared to django's

#

@teal bane

teal bane
#

hello

#

@median loom can you guide me please

median loom
#

i haven't actually used flask that much

#

i once started a project with it but quit halfway

#

but flask is simpler and a easier to learn than django

teal bane
median loom
#

i know them

#

and have used them both

#

but i don't have much experience and expertise

teal bane
median loom
obtuse kite
vestal hound
#

@obtuse kite if you want help

#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

naive rock
#

I'm working on a program that makes requests to several different APIs(GET, POST, PUT). Mostly Get and and PUT. Right now the project takes roughly 40 minutes to finish mainly because for PUT, I can only update 1 item at a time.

How can I make it fast? I looked into multithreading and came across gerequests. Is gerequests something I should look into?
https://stackoverflow.com/questions/38280094/python-requests-with-multithreading

woeful vapor
#

what would be faster asyncio or gevents?

#

I have a flask endpoint running right now and my bottle neck is this one tasks that does a look of async requests.gets but I feel like my implementation is off

#

I'm running gunicorn with gevent config and regular flask. The flask app is monkey patched with gevent so in theory my async stuff should execute pretty fast

woeful vapor
#

    loop = get_or_create_eventloop()
    future = asyncio.ensure_future(multiCallPrice(tokentemp))
    prices = loop.run_until_complete(future)
#

Idk why but I have this in there itโ€™s the only way I can get it to run

#

def get_or_create_eventloop():
    try:
        return asyncio.get_event_loop()
    except RuntimeError as ex:
        if "There is no current event loop in thread" in str(ex):
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            return asyncio.get_event_loop()
#
async def multiCallPrice(loopOver):
    tasks = []
    timeout = ClientTimeout(total=40)

 

    async with ClientSession(timeout=timeout) as session:
        for token in loopOver:

            task = asyncio.ensure_future(async_get_request(session, url, token['token'], token['decimal'], shareAmount))
            tasks.append(task)

       responses = await asyncio.gather(*tasks)
        return(responses)```
jolly star
#

hey how do you make it such that your flask server is updated every x times
i am using a mysql database and when any database changes are made it doesnt reflect in the webpage

inland oak
#

something like... simple js script which checks from time to time update from your backend, and updates the page

#

basically client-side code

#

your backend should expose its data in form of JSON API for this

jolly star
#

no idea what that is but i think i should explain it again
i added a record to the database and restarted the flask app the change was there
but when i removed that record and refresh the page the record stays
so i think i need something that restarts as such my flask app every x times

#

so the changes are visible every time

#

the sql is updated

inland oak
#

you are right now rendering page as fixed HTML document

#

you need to change output of your information to JSON format and having available at some end point

#

while rendering your view page with addition of JS code which fetches data from your JSON API endpoint

#

then you can add to js code some addition, which will check for updates and rerender it automatically

jolly star
#

okay what do i need to do

inland oak
#

I just wrote it.

#

google for some more information about JSON API and JS fetches

jolly star
#

ok

grave hawk
#

How do you guys do queue management with fastapi?
I have built a ML API deployed on GCP Cloud Run with a docker image but on some cases the response takes time and I would rather it goes into a queue like redis or something. I did achieve that by making a docker compose but then I couldn't deploy docker-compose with CI CD on GCP. I don't want to get into kubernetes as it'll be too complex for a small scale solution like mine.

prisma canopy
#

I am making a flask website with use of bootstrap. When I click on options provided on nav bar, sometimes some options changes their end point to the file from which they are being rendered and give not found errorbasketballpls help

whole hearth
#

Flask or Django Lets fight ๐Ÿ˜‚

obtuse kite
# vestal hound <@!547483019641094155> if you want help
image= models.ImageField(upload_to='uploads/', blank=True, null=True)
    thumbnail= models.ImageField(upload_to='uploads/', blank=True, null=True)
    date_added= models.DateTimeField(auto_now_add=True)


    class Meta:

        ordering = ('-date_added',)
    
    def __str__(self):
        return self.name
    
    def get_absolute_url(self):
        return f'/{self.category.slug}/{self.slug}/'
    
    def get_image(self):
        if self.image:
            return 'http://127.0.0.1:8000' + self.image.url
        return ''
    
    def get_thumbnail(self):
        if self.thumbnail:
            return 'http://127.0.0.1:8000' + self.thumbnail.url
        else:
            if self.image:
                self.thumbnail = self.make_thumbnail(self.image)
                self.save()

                return 'http://127.0.0.1:8000' + self.thumbnail.url
            else:
                return ''
    
    def make_thumbnail(self, image, size=(300, 200)):
        img = Image.open(image)
        img.convert('RGB')
        img.thumbnail(size)

        thumb_io = BytesIO()
        img.save(thumb_io, 'JPEG', quality=85)
        thumbnail = File(thumb_io, name=image.name)


kind oyster
#
print('Hello world!')
scenic dove
#

@digital hinge @opaque rivet thanks both

#

Hello

#

So i have this form that lets the user make a poll and add choices to it

#

It consists of 2 ModelForms on for the quiestion model and the other for the choice model

#
forms.py



from django import forms
from .models import Question
from .models import Choice




class NewPollForm(forms.ModelForm):
    class Meta:
        model = Question
        labels = { 
            "questionText":"Poll question"
        }

        fields = ("questionText",)



class NewChoicesForm(forms.ModelForm):
    class Meta:
        model = Choice
        labels = {
            "choiceText":"Choice"
        }
        fields = ("choiceText",)
#
models.py


from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()




class Question(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
    questionText = models.CharField(max_length=150)
    datePublished = models.DateTimeField(auto_now_add=True)

    def str(self):
        return self.questionText


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choiceText = models.CharField(max_length=200)
    choiceVotes = models.IntegerField(default=0)

    def str(self):
        return self.choiceText
#

I want to let the user be able to add as many choices as they want
Like there be a (+) button or (add another choice) in the form in the image above

#

Oh i forget

#

Here's my view that handles this page

#
views.py



def newpoll(request):
    if request.user.is_authenticated == True :
        pass
    else:
        return redirect("users:signup")
    if request.method == "POST":
        qform = NewPollForm(request.POST)
        cform = NewChoicesForm(request.POST)
        if qform.is_valid():
            newpoll = qform.save(commit=False)
            newpoll.user = request.user
            newpoll.datePublished = timezone.now()
            newpoll.save()
            cform.instance.question = newpoll
            cform.save()
            return redirect("polls:details", pollid=newpoll.pk)
        else:
            return render (request, "polls/newpoll.html", {"qform":qform, "cform":cform})
    else:
        qform = NewPollForm()
        cform = NewChoicesForm()
        return render (request, "polls/newpoll.html", {"qform":qform, "cform":cform})
#

Thanks in advance

tepid fern
#

I know this isn't the right place to ask about react but anyways ........
When I do import { Navbar, Nav, NavDropdown, Form, Button, FormControl } from 'react-bootstrap';
I get the error Module not found: Can't resolve 'react-bootstrap in file_location_here
I tried doing npm install react-bootstrap bootstrap@4.6.0
but the results are unchanged
What's the problem?

wraith cloak
#

How to get started on a basic website, ik there is flask but any docs or starters.

inland oak
inland oak
# wraith cloak ah tysm

a little bit outdated by few years, but still good one
in most of them everything is still correct, but in some places syntax got changed
in my opinion it is even good because allows you to think more what needs to be done instead of copy pasting

wraith cloak
#

ill just read it

#

and refer to it

native tide
#

New Release logo_django2

I am deeply in love with Python 3 and it's ecosystem! gem_red

Hello guys, a couple weeks ago i published my first book on Django 3 and want to share it with you: https://www.amazon.com/Django-3-Beginners-Andrey-Bulezyuk-ebook/dp/B095V5P2QM/ref=tmm_kin_swatch_0?_encoding=UTF8&qid=&sr=
I'd be glad to receive honest feedback!

wraith cloak
#

seems sus

native tide
#

Why?

steel reef
#

I created token authentication system in Django rest framework, after getting the token, how should I authenticate myself?? any suggestions

#

is a UI necessary?

obsidian steeple
#

damn i just wanted to try flask

#

flask is installed

native tide
#

@steel reef UI is not needed. You need to pass the JWT Token (generated in backend) with every other request unter "auth" "bearer <JWT>"

burnt night
#

So uhm...
cough

#

This is NOT...
What I wanted

#

Is there a way to have html render correctly from a string?

#

Using Flask

inland oak
#

I am choosing to learn some front end framework to complement my django rest framework
what would you recommend as the most easiest and nicest choice, preferably closer to django approach in development?
Angular? Vue? React?

burnt night
#

Nvm, using Markup worked