#web-development

2 messages ยท Page 188 of 1

inland oak
#

it will protect them from tampering

#

if JWT Token will be not decoded back with your secret key, then it was tampered or expired

#

You can delete his cookie immediately with request sent to server about room deleting

lime frigate
#

Okayyy i will definitely try it

#

Thanks for the info mate

inland oak
#

u a welcome

#

xD, the problem was solved with just having stuff client side

#

no delay between requests = no problem

#

there will be still micro delay though, since stuff in client browser is launched in async mode

#

but that should be not an issue

fast lava
#

pls can someone help me

dusk portal
#
 <form id="LoginForm" method="POST">
                        {% csrf_token %}
                        {{form}}
                        <button type="submit" class="btn">Login</button>
                        <a href="{% url 'users:register' %}">Have an account?Login</a>
                    </form>
#

why im not getting the input type n all stuff by django

#

@eternal blade waiting for u lord

eternal blade
dusk portal
eternal blade
#

yes

#

And the code for the form

dusk portal
#
<div class="account-page">
    <div class="container">
        <div class="row">
            <div class="col-2">
                {% load static %}
                <img src="{% static 'login.png'%}" width="100%">
            </div>
            <div class="col-2">
                <div class="form-container">
                    <div class="form-btn">
                        <span onclick="login()">Login</span>
                        <span onclick="register()">Register</span>
                        <hr id="Indicator">
                    </div>

                    <form id="LoginForm" method="POST">
                        {% csrf_token %}
                        {{form}}
                        <button type="submit" class="btn">Login</button>
                        <a href="{% url 'users:register' %}">Have an account?Login</a>
                    </form>

                    <form id="RegForm" method="POST">
                        {% csrf_token %}
                        <input type="text" name="username" placeholder="Username">
                        <input type="email"  name="email" placeholder="Email">
                        <input type="password" name="password" placeholder="Password">
                        <input type="password" name="confirm_password" placeholder="Confirm Password">
                        <button type="submit" class="btn">Register</button>```
#

showed so much to tell

#

using js in this too

#

and this page by js combines 2 form

#

main is

                     <form id="LoginForm" method="POST">
                        {% csrf_token %}
                        {{form}}
                        <button type="submit" class="btn">Login</button>
                        <a href="{% url 'users:register' %}">Have an account?Login</a>
                    </form>

                    <form id="RegForm" method="POST">
                        {% csrf_token %}
                        <input type="text" name="username" placeholder="Username">
                        <input type="email"  name="email" placeholder="Email">
                        <input type="password" name="password" placeholder="Password">
                        <input type="password" name="confirm_password" placeholder="Confirm Password">
                        <button type="submit" class="btn">Register</button>```
native tide
#

Hi can anyone help me to make a simple register and login system?

I made a registering one but im not sure if it's correct pls check You always help me please help me now too

cerulean badge
#

how do you disable validation for an input field? (only one input field not the whole form)

fossil loom
dusk portal
#

I'm creating kind of Roadmap site so I will first ask usersome question's what he wanted to learn then will give result according to what he want to learn how can I do it on web (using Django in web) @eternal blade

zinc narwhal
#

Hi guys I'm new to django and I have to add an excel file upload to my web app, can anyone help me with that?

wintry cape
#

is there anyone good with Fastapi ? i have some bug with alembic and postgreSQL connection

rotund perch
#

Any suggestions on a good hosting provider? (To host django api or app)

rotund perch
manic crane
#

hmm same but i dont mind a bit of tutorials to show my way round cause i heard its really good

rotund perch
#

Okay thanks for the suggestion!

manic crane
#

no problem

eternal blade
worthy oar
#

@rotund perch asc wr wb

rotund perch
#

?

opaque rivet
#

@rotund perch do you just need a RDP?

rotund perch
opaque rivet
#

No diff

rotund perch
#

I mean like performance

rotund perch
opaque rivet
#

I use AWS but if you just want an RDP there are cheaper providers

#

Like hetzner or DO

rotund perch
#

Okay, Thanks !

dusk portal
opaque rivet
#

@dusk portal that's the opposite of learning...

eternal blade
fossil pond
#

Hello guys. So I changed my html file to have a lot of blocks to make it easy to read. But the only thing that's running is the loading screen in an infinite loop. What's surprising is the fact that even when I comment out the loading screen div the only thing that appears is the loading screen and not the actual webpage.

#
{% load static %}

{% block title %} 
    Rhitam's Website 
{% endblock %}

{% block content %} 
    {% include 'welcome-content.html' %} 
{% endblock %}

<!-- {% block container %}
    <div class="loader-wrapper">
        <div class="loader">
            <div class="image">
                <i class="fa fa-dumbbell"></i>
            </div>
            <span></span>
        </div>
    </div>
{% endblock %} -->

{% block javascript %} 
    <script src="{% static 'main/welcome/base.js' %}"></script> 
{% endblock %}```
#

base.html doesn't even have the javascript

#

even when I comment out the entire js the same thing happens

fossil pond
#

Any help is appreciated! I'm having to put repetitive html codes on every webpage because of this.

opaque rivet
fossil pond
opaque rivet
fossil pond
opaque rivet
#

does welcome-content.html have any JS

tired vine
#

Hello, will the SEO be impacted with a .ps domain name ? (I want to name my site comicu.ps, which stands for ComicUps)

dusk portal
ionic raft
#

@opaque rivet How did the design changes work out? What did you end up with?

ionic raft
opaque rivet
#

@ionic raft ended up having black buttons on large viewports and light blue buttons on mobile. Now animating the site and trying to get a draggable grid (and it's a pain)

dusk portal
#

;-;

#

pain

#

@ionic raft

#

help me out

#

;-;

ionic raft
ionic raft
dusk portal
ionic raft
# dusk portal u know web scraping

Very little. I worked briefly with Beautiful Soul and Selenium about 3-4 months ago. I am very rusty and would be surprised if I could help with complex troubleshooting.

dusk portal
ionic raft
# dusk portal I wanna scrape Udemy Courses by some data which user will enter in my form

Well, I would start by checking their terms of service for such scraping. When a paid service doesn't have an API, going to web scraping can be legally problematic.
That said, if you are looking to scrape what courses are available, my sense would be that Selenium may be a good starting point.
IIRC you can also check the URL with the path robot (specifics for you to research) to see what scraping Udemy allows.

dusk portal
#

I'm in a hackathon

#

They have a docs too

#

But ig for me hard to follow

grim seal
#

Anyone here familiar with the Pyramid framework and it's official Quick Tutorial? I've reached a step in the tutorial where suddenly none of my code runs, with the last error in the traceback being: ModuleNotFoundError: No module named 'tutorial'. This after successfully completing each step of the tutorial up until my PC crashed. Now none of my tutorial code runs, and I'm hoping that someone knows the tutorial because otherwise it's one hell of a lot of coding to show here

calm plume
#

Their API provides a decent bit of information

#

Also, scraping them Udemy is a violation of their robots.txt: https://www.udemy.com/robots.txt. They only allow things like that on their /api-2.0/ route, which you'd be better off just using through traditional REST API interaction methods.

ionic raft
#

OMG... ๐Ÿ˜„
So, you know when you've been trying to find out why you can't get the pk from the get_context_data function in the view, and then a couple of hours later you realize you built the url for the CreateView WITHOUT passing a pk over?
Yeah...that.
๐Ÿ˜„

dusk portal
mild marsh
#

does anyone know how to fix this probblem im trying to run a flask server but it seems to not working have all requirements installed

regal fossil
#

Hi i am working in django
I have a html form with hidden field.
I tried to get the data as

If request.method== "POST":
    data  = request.POST.get("field nsme")

But i am getting nothing.

native tide
#

anyone knows how to make firefox in dark mode PES_Think

worthy lake
#

if I had to guess i would say modifying userChrome.css

ionic raft
# dusk portal so i cant scrape courses link with title to give like a roadmap as it's our hack...

As was suggested, I'd check https://www.udemy.com/robots.txt to check what they allow. If you try to scrape in contradiction to their robot.txt it is an illegal activity. If you're engaging in an activity with a hackathon that is asking you to engage in such activity I would suggest considering another activity.

In short, I expect that a paid service like Udemy wants you to use their API. They get control over the data exchange that way and everyone is happy (and behaving in a legally acceptable manner).

Web scraping is filled with ethical grey areas and no-goes.

opaque rivet
#

Who is ever going to enforce webscraping? It's impossible.

humble sparrow
#

Pls I need help

#

Having errors trying to get the Book_id

#

Showing me function object has no attribute โ€˜objectsโ€™

vestal hound
#

post text

#

not screenshots

#

and especially not pictures of screens

humble sparrow
#

Def index(request):
Context ={
โ€˜Bookโ€™ : Book.objects.all()
}
render(request, โ€˜Book/index.html, context)

#

While loading it on the page
It says the function attribute has no attribute โ€œobjectsโ€

native tide
#

Is it because you re-defined Book as a function ?

#

maybe try def book

elder nest
#

how would I update a site with an event without reloading the page in quart?

ionic raft
dusk portal
#

How can I do

#

I have 6 hrs left

#

U know any site any course
Even 1

#

Which I can scrape n can show

#

I can win

#

We have other things done

spice spindle
#

ok someone please help

#

im trying to hyperlink the word accommodations to the id tag "faq13" but its not working

#

the word is clickable but it takes you nowhere

#

what am i doing wrong?

tawny pollen
#

Get the metadata for the required field and use it to query the required field data
what does "query" mean ? this is django. thanks.

ionic raft
# spice spindle

I am not completely clear on what you're asking for. But, when you use an <a> anchor tag in html for an in-page hyperlink you need two parts to it. If on the other hand, you're trying to create a link outside the site, then the href value you have is not going to work.

An in-page anchor tag should have two parts. This first anchor tag is the clickable link:

<li><a class="heading-link" href="#1-Introduction">Introduction</a></li>```
This second part is where the above link will take you to in-page:
```html
 <h3 class="heading-link"><a id="1-Introduction">1. Introduction</a></h3>```
As a rule, posting screenshots for code is not very helpful. It is much better to post the code in markdown style, with back-ticks.
#

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

ionic raft
#

As a side note, I just released v0.3.0 of LanesFlow. There's now an hour tracker ๐Ÿ™‚

#

There are two options. You can either track hours for a pool of prepaid hours for the client organization, or you can go with billable hours. This is the prepaid hours option in play.

#

I think this needs a few filters....But otherwise, I welcome any thoughts. If anyone has experience with this sort of thing and has feedback, please share.

spice spindle
ionic raft
regal fossil
#

How to get full video url in django with FileField?

ionic raft
spice spindle
ionic raft
#

Use three backticks...

#

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

ionic raft
spice spindle
#

<h2 id="faq13">I am looking for accommodation for the event, where is best to stay?</h2>

#

<a href="#faq13">accommodations</a>

#

first line is on my FAQ page, second line is on the home page

regal fossil
spice spindle
#

im trying to link the word accommodations to the id=faq13 on the FAQ page

ionic raft
ionic raft
spice spindle
#

but I don't know what I would put there in my case

ionic raft
spice spindle
#

sorry I'm like 3 weeks into coding

ionic raft
spice spindle
#

oh

#

ok let me try it

ionic raft
spice spindle
#

<h2> <a id="faq13"></a>

#

still didn't work

ionic raft
spice spindle
#

i dont know how to

ionic raft
#

Just copy the two tags...not the whole html file

#

I'm going to type them up the way I'd do it...give me a minute...

spice spindle
#

i have been copy and pasting

ionic raft
spice spindle
ionic raft
ionic raft
spice spindle
ionic raft
#

I suggest you work out how to read the following along with copy/paste

#

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

ionic raft
ionic raft
#

Ok. I've got to go to bed. Best of luck. I know you'll get there....

spice spindle
#

thank you for real, i spent hours trying to figure this out

ionic raft
#

On a completely side note, I just got my web application emailing out html emails when events happen ๐Ÿ˜„

#

I have to say, seeing a polished email arriving from an automated web application like that...makes my heart very happy ๐Ÿ™‚

#

Thank goodness for CONST variables ๐Ÿ˜„

pulsar girder
#

Hello? Anyone here wants to make a django project with me

grave raft
#

How can I filter on the basis of queryset of foreign key in Django ??

#

`class CsvFile(models.Model):
file = models.FileField(upload_to='csv/' )

class FileSearch(models.Model):
file = models.ForeignKey(CsvFile, on_delete=models.CASCADE)
pattern = models.CharField(max_length=500)
status = models.CharField(max_length=100)`
Like these are the model
qs = CsvFile.objects.filter(file__contains="xxx")
now how can I get all File search whose file foreign key is in qs

opaque rivet
#

@grave raft qs.filter(file_set=CsvFile object)

cerulean badge
#

(django) i have a order model and i have thought of adding datetime fields placed paid dispatched delivered can you suggest me improvement to the model?

#

what are the stages of an order?

ionic raft
cerulean badge
ionic raft
cerulean badge
#

the fields i mentioned are datetime fields

ionic raft
cerulean badge
#

do you think i should add a field which would mark the order is being worked on?

cerulean badge
#

i have one more question how do i provide the interface for disptached, delivered and paid (in case of cod) in my custom admin dashboard?

cerulean badge
#

how about empty post form with csrf token for dispatched, delivered and paid stages which sets their values?
and showing the form corresponding to current stage?

native tide
#

How can I dynamicly calculate in django, days delta along queryset

wide canyon
#

Is sending an article i wrote on django here against the rules?

native tide
#

haha wouldn't be harmfull : D

#

mind helping out ?

wide canyon
#

Annotate should do that i guess

native tide
#

Basicly I have a model with a field, date_to, I wanna calculate how many days are for each item

wide canyon
#

Annotate should work

native tide
#

so i wanna add a field, expires_in_days = date_to - now()

wide canyon
#

ohhhh

native tide
#

yea for example lets asume, item expires on 6.9.2021

#

i wanna add a field expires_in_days = 1

#

6.9.2021 - 5.9.2021

#

etc..

wide canyon
#

can you add it as a class method and call it whenever you need instead?

native tide
#

i cant do order by then haha : D

#

tought about property

#

as well

wide canyon
#

I hope I'm not giving bad advice

#

Annotate and order by annotated field

#

Unless you want to do it in multiple places

#

We'd have to think of something more efficient

native tide
#

i need in multiple ...

#

hmm

#

even if i do forloop, i cant after that execute order_by

#

i can by sorted and key

wide canyon
#

found something on SO

#

Daniel Roseman's solution makes a calculated field an attribute of a Model, however it does not make it accessible via QuerySet methods (eg. .all(), .values()). This is because QuerySet methods call the database directly, circumventing the django Model.

Since QuerySets access the database directly, the solution is to override the Manager's .get_queryset() method by appending your calculated field. The calculated field is created using .annotate(). Finally, you set the objects Manager in your Model to your new Manager.

Here is some code demonstrating this:

models.py

from django.db import Model

class InvoiceManager(models.Manager):
    """QuerySet manager for Invoice class to add non-database fields.

    A @property in the model cannot be used because QuerySets (eg. return
    value from .all()) are directly tied to the database Fields -
    this does not include @property attributes."""

    def get_queryset(self):
        """Overrides the models.Manager method"""
        qs = super(InvoiceManager, self).get_queryset().annotate(link=Concat(Value("<a href='#'>"), 'id', Value('</a>')))
        return qs

class Invoice(models.Model):
    # fields

    # Overridden objects manager
    objects = InvoiceManager()```
Now, you will be able to call .values() or .all() and access the newly calculated link attribute as declared in the Manager.

It would have also been possible to use other functions in .annotate(), such as F().

I believe the attribute would still
#

basically overriding the default manager

native tide
#

hmm

#

yea

charred epoch
#

hey im trying to use render_template from flask library but i get an error

#

the error is this:

#
Traceback (most recent call last):
  File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\flask\app.py", line 2070, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\flask\app.py", line 1515, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\flask\app.py", line 1513, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\flask\app.py", line 1499, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "c:\Users\gg\Desktop\html\1.py", line 8, in home
    return render_template("web.htm")
  File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\flask\templating.py", line 148, in render_template
    ctx.app.jinja_env.get_or_select_template(template_name_or_list),
  File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\jinja2\environment.py", line 1068, in get_or_select_template
    return self.get_template(template_name_or_list, parent, globals)
  File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\jinja2\environment.py", line 997, in get_template
    return self._load_template(name, globals)
  File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\jinja2\environment.py", line 958, in _load_template
    template = self.loader.load(self, name, self.make_globals(globals))
  File 
"C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\flask\templating.py", line 59, in get_source
    return self._get_source_fast(environment, template)
  File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\flask\templating.py", line 95, in _get_source_fast
    raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: web.htm
#

even though my web.htm is in the same folder with the python file

#
@app.route("/")
def home():
    return render_template("web.htm")
cerulean badge
#

(context django) i have a order model with datetime fields placed, paid, dispatched, delivered
i want to show status of the order depending on these fields should i write model method or filter?

dusk portal
#

@ionic raft

#

hey

#

r u there

boreal epoch
#

Already pretty decent with Python, but Iโ€™ve decided to rewrite the backend of a personal project in Django (I tried NodeJS first but it just feels like it barely works lol). Iโ€™ve never used it before, but have been interested for a while since I like using Python in general. Whatโ€™s the best tutorials you guys know of for building APIs with Django?

native tide
#

Two scopes of django

#

its a book, highly recommend

#

includes best practices and good explanation

velvet yew
#

How can I make custom responses for Django REST framework's authentication? I'd like to replace {'detail': 'Authentication credentials were not provided.'} and {'detail': 'Invalid username/password.'} etc. with custom responses

broken mulch
#

can my frontend React app establish a websocket connection to my backend django server?

#

if so, how would I open the websocket client and what library would I use in React?

#

pls ping on answer

#

I just need the libraries and their source / docs

opaque rivet
velvet yew
ancient obsidian
#

Django or Flask? Which one should I use?

opaque rivet
opaque rivet
velvet yew
fossil pond
#

Hey guys! I want to make a scrollbar which when scrolled scrolls more than what the normal one allows with a bit of momentum

#

Any help is appreciated

opaque rivet
#

Probably helps

terse dust
#

Hi, I am using Python flask

#

I need help

#

How can I handle file upload?

#

Like

#

I have input type file

#

How can I handle that?

fossil pond
lime mist
#

Hi, I'm trying to deploy my socket.io server on Heroku but it's throwing this error on heroku when ever my client tries to connect:

2021-09-05T17:40:11.114390+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/socket.io/?transport=polling&EIO=4&t=1630863609.333491" host=MY_HOST request_id=MY_REQ_ID fwd="MY_PUB_IP" dyno= connect= service= status=503 bytes= protocol=https
#

This is my Procfile:
worker: uvicorn server:app

opaque rivet
#

@fossil pond copy the github file

#

Then reference it in the head of the html file

boreal epoch
frank shoal
lime mist
# frank shoal Add `--port $PORT`
2021-09-05T18:09:02.227365+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/socket.io/?transport=polling&EIO=4&t=1630865341.2534761" host=HOST request_id=3RID fwd="PIP" dyno= connect= service= status=503 bytes= protocol=https```
#

worker: uvicorn server:app --host 0.0.0.0 --port $PORT

frank shoal
#

Ah, you need a web: ... line

lime mist
#

ic let me try that one real quick

lime mist
# frank shoal Ah, you need a `web: ...` line

okay so it did connected but it instantly throw this:

2021-09-05T18:17:30.317827+00:00 heroku[router]: at=info method=POST path="/socket.io/?transport=polling&EIO=4&sid=P3767GBFupznddJ4AAAA" host=HOST request_id=RID fwd="PUBIP" dyno=web.1 connect=0ms service=13ms status=200 bytes=198 protocol=https```
#

and ofcouse my client raised an error too once this was raised in server

frank shoal
#

status=200

#

That's good

lime mist
#
Traceback (most recent call last):
  File "c:\users\maila\appdata\local\programs\python\python39\lib\threading.py", line 954, in _bootstrap_inner       
    self.run()
  File "D:\Coding Stuff\UpWorkStuff\LinkedInDelivery\li_worker\src\helpers\sio_client.py", line 16, in run
    self.sio_client.connect(server_url)
  File "C:\Users\maila\.virtualenvs\li_worker-JBpAobyS\lib\site-packages\socketio\client.py", line 338, in connect   
    raise exceptions.ConnectionError(```
#

but the client connected then disconnected instantly

frank shoal
#

Are you using websocket?

lime mist
frank shoal
#

๐Ÿคท

ionic raft
# fossil pond Thanks this helped a lot!

It's funny how that works. I found out the hard way the difference between a browser reset and a hard-reset. And even then, incognito can sometimes be the only way to get through it. Port numbers for Flask dev was my nemesis when I was coding Flask. If you ran multiple projects and wanted different ports...watch out!

ionic raft
# native tide Two scopes of django

I highly recommend two-scoops. I'm still working my way through it. But as my Django experience grows, my ability to make use of that wonderful book grows also.

native tide
#

haha glad we have someone who read/is reading it : )

#

shoutout to the writers, they did amazing job on it

#

pure experience and knowledge

#

read only that book you'll have django in palm ๐Ÿ˜›

opaque rivet
#

what do we think about the look of this?

#

thinking to add more contrast.

#

and change the logo location to the center here.

#

just spent ages animating it all and adding drag n' drop items. Loving how it's so reactive.

cloud parrot
#

It looks pretty nice,

stray notch
#

can I clear my django-q queue from the command line? I haven't been able to clear it from the admin interface, because my browser crashes when django-q is running ๐Ÿค”

#

I'm using django ORM as a message broker

fickle basin
#

hello

#

i get this error while just setting up django from docs after adding the the methode

class game_selection(models.Model):
    game_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.game_text
        
    def was_published_recently(self):
        return self.pub_date = timezone.now() - datetime.timedelta(days=1)
#
File "/home/noah/Bureau/Django/steamseller/library/models.py", line 12
def was_published_recently(self):
TabError: inconsistent use of tabs and spaces in indentation
native tide
#

Hey guys,

I've always tried to learn flask and all, I did some goofy things here and there but never got to deploy them.

What's the best way to deploy a flask app ? I always encounter these examples WSGI, but I feel like I don't understand anything and that I have to do more reading about networking and whatnot.

Sometimes I even feel somewhat "scared" and hesitate to read about it.

Does anyone have a good place to start ?

stray notch
#

@fickle basin I think you should check that you are using 4 spaces for each indent

fickle basin
#

it is 4 spaces

#

it's working after copy/past ?? thats wierd

#

sublimetext is set on Tab Size : 4

#

that weird

stray notch
#

maybe it's the 8 spaces on the line before?

stray notch
ionic raft
# native tide haha glad we have someone who read/is reading it : )

I asked around for good books on Django before I started my first Django web app (with an idea I'm excited by). I used it to brush up on some best practices and get pointers. I expect to dip back into it over the years to come. LanesFlow is now some 28,095 total lines of code, with over 10 applications. You could say that Two Scoops has been instrumental in this newbie's journey in Django (didn't know Python Apr 15, 2021, or Django Jul 8, 2021).
And yes, amazing job by the writers...

ionic raft
stone flax
#

hey all, are there any alternatives to Google Analytics for Flask out there? I'm looking to use a self-hosted alternative, or maybe even considering my own data capture+analytics system storing info from each request from scratch. but that seems a bit too much. I'd much rather leverage an open source solution if there is any

stray notch
stone flax
#

thanks! I'll check it out

lucid marsh
#

I'm trying to deploy a flask_socket io server with mod_wsgi+apache2, however, it doesnt seem to work, anybody knows how to run flask_socketio server with mod_wsgi+apache2 on vps?

versed python
lucid marsh
#

oh ok

#

problem is i already deploy the old flask app with apache2

#

well i mean, i can switch to nginx

versed python
#

yeah do it, you wont find good tuts for apache

desert cradle
#

I want to hand over the parameters to Django's redirect. What should i do?

#

flask code:
return redirect(url_for("views.act_date", user=params))

inland copper
#

hmm

lucid marsh
versed python
lime mist
#

Can someone help me understand how requests are handled in an ASGI server? What async really does in situations when say 100 people are requesting the server? Does it resolve request one my one? if so then what's the use of it being async? If not how does it serves these requests?

raven harbor
inland oak
#

first user requests the server, and got stuck in a long await operation

#

during this time I think in theory server supposed to be able to process another user ๐Ÿค”

#

I could be wrong though

#

anyway, multi worker async server exist anyway

#

so threading can be applied too

#

to process users in multiple manner

opaque rivet
#

Doesn't WSGI Django use Asyncio to process requests asynchronously though?

lime mist
#

yes that's my main confusion, I don't understand the difference between async request and spinning threads. I made a server that runs OCR on image with an ASYNC server and while it was processing image it didn't accept new connect so I had to implement it so that it receives a request and puts it onto a thread. So I don't understand what ASYNC is suppose to do when it's clearly not working?

inland oak
#

i know for sure only that

#

ASGI server is needed in order to work with django channels/web sockets to make real time chat

lime mist
inland oak
#

I hope there is some good book about them

lime mist
opaque rivet
#

@lime mist From my knowledge, WSGI applications are functions which take in a request and return a response. So in theory requests are handles synchronously.

The difference with ASGI applications is that it's a callable which is async, and it awaits the response. So the server can handle other requests while the response is being awaited.

My confusion is that django uses asyncio already to handle requests, maybe I need to read about that more.

inland oak
lime mist
inland oak
#

I saw a mention of asyncio being used as job queue at least

lime mist
inland oak
opaque rivet
#

Asyncio is probably used for async views. But if you use async views in a WSGI server do you even get any benefit? I don't think so, since it's still 1 request at a time.

inland oak
#

it the library is not async friendly, it will not help that it is awaited, because it will still block the thraed

#

for example, it will not matter if I put Selenium library into async

#

or if I will use requests library with async

#

it is not async friendly

#

I need aiohttp for that

opaque rivet
#

@lime mist what asgi server were you using? Also what's OCR?

inland oak
#

recognizing stuff in images, characters I think

lime mist
#

A minute, let me share my source

opaque rivet
#

Ah okay

lime mist
inland oak
#

starting from python 3.9

#

you could launch async not friendly processes

#

in a second thread!

opaque rivet
#

It would be cool connecting a computer vision lib to a CNN to detect images in real time

lime mist
#
import socketio
import json
from helpers import processTextifyRequest

sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins="*")
app = socketio.ASGIApp(sio)

online = 0
like = 0


@sio.event
async def connect(sid, environ):
    print(f"[CONNECTED] {sid}")
    global online
    online += 1

    await sio.emit("serverStats", json.dumps({"online": online, "like": like}), to=sid)
    await sio.emit("updateOnline", online)


@sio.event
async def getText(sid, data):
    await processTextifyRequest(sio=sio, sid=sid, data=data)


@sio.event
async def doLike(sid):
    global like
    like += 1
    await sio.emit("updateLike", like)


@sio.event
async def disconnect(sid):
    print(f"[DISCONNECTED] {sid}")
    global online

    online -= 1
    await sio.emit("updateOnline", online)
inland oak
#

thus, making sure that environment remains async friendly

lime mist
lime mist
opaque rivet
#

ngl I'm lost with this ๐Ÿฅด seems like more async / asgi reading is needed

lime mist
opaque rivet
#

What if you use asyncio.gather() somehow to concurrently run coroutines?

#

I can't really explain it well

#

But when I was working with async, just awaiting coroutines was just like sync code. I had to use asyncio.gather() etc

lime mist
cobalt sentinel
#

how to learn django??

#

I'm beginner to this

thorny quartz
unreal bolt
#

how to improve this? (forgot to tell its js)

#
if (item0Inner == p && item1Inner == p && item2Inner == p) return [true, p, item0.id, item1.id, item2.id];
if (item3Inner == p && item4Inner == p && item5Inner == p) return [true, p, item3.id, item4.id, item5.id];
if (item6Inner == p && item7Inner == p && item8Inner == p) return [true, p, item6.id, item7.id, item8.id];

if (item0Inner == p && item3Inner == p && item6Inner == p) return [true, p, item0.id, item3.id, item6.id];
if (item1Inner == p && item4Inner == p && item7Inner == p) return [true, p, item1.id, item4.id, item7.id];
if (item2Inner == p && item5Inner == p && item8Inner == p) return [true, p, item2.id, item5.id, item8.id];

if (item0Inner == p && item4Inner == p && item8Inner == p) return [true, p, item0.id, item4.id, item8.id];
if (item2Inner == p && item4Inner == p && item6Inner == p) return [true, p, item2.id, item4.id, item6.id];```
native tide
#

put them in a tuple

#

then compare the tuple

unreal bolt
#

i dont even know what a tuple is (,:

native tide
#

i.e. instead of a==1 and b==2

#

if (a,b) == (1,2)

unreal bolt
#

so would be like:

if ((item0Inner, item1Inner, item2Inner) == p)```?
#

im trying to understand how it works

native tide
#

== (p,p,p)

#

in that case

unreal bolt
#
if ((item0Inner, item1Inner, item2Inner) == (p, p, p))```
native tide
#

ye that will work

#

it's just checking 1 object rather than 3 now.

#

so reduces the 'ands' and '==' you have to do

unreal bolt
#

hmmm cuz this doesnt exist right?

if (item0Inner == item1Inner == item2Inner == p)
native tide
#

not in python the way you would think. also chaining them can causes issues depending on the type

#

cos of dunder methods

unreal bolt
#

okay

native tide
#

so there are python magic methods

vestal hound
#

no, I mean, why do you think a == b == c == d won't work?

native tide
#

that tell a type how to * or / or other stuff. depending on what they are next to. and wheter thats on the left or right

vestal hound
#

(in the general case, assuming __eq__ is sensibly defined)

native tide
#

ye sorry. that one probably does work

#

i was thining of something else

unreal bolt
#

what is the problem?

vestal hound
#

e.g.

native tide
#

but looks shit too compared to comparing tuples IMO

vestal hound
#

!e

print(1 < 3 < 6)
print(1 < 7 < 6)
lavish prismBOT
#

@vestal hound :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | False
vestal hound
#

whereas in most other languages you'd need to do something like (1 < 3) && (3 < 6)

unreal bolt
#

oh

#

well, now i have it like this:

if ((item0Inner, item1Inner, item2Inner) == (p, p, p)) return [true, p, item0.id, item1.id, item2.id];
if ((item3Inner, item4Inner, item5Inner) == (p, p, p)) return [true, p, item3.id, item4.id, item5.id];
if ((item6Inner, item7Inner, item8Inner) == (p, p, p)) return [true, p, item6.id, item7.id, item8.id];

if ((item0Inner, item3Inner, item6Inner) == (p, p, p)) return [true, p, item0.id, item3.id, item6.id];
if ((item1Inner, item4Inner, item7Inner) == (p, p, p)) return [true, p, item1.id, item4.id, item7.id];
if ((item2Inner, item5Inner, item8Inner) == (p, p, p)) return [true, p, item2.id, item5.id, item8.id];

if ((item0Inner, item4Inner, item8Inner) == (p, p, p)) return [true, p, item0.id, item4.id, item8.id];
if ((item2Inner, item4Inner, item6Inner) == (p, p, p)) return [true, p, item2.id, item4.id, item6.id];
```something else i could do?
vestal hound
#

okay back up a bit

unreal bolt
#

xd

vestal hound
#

what are you trying to do?

unreal bolt
#

tic tac toe ifs to check if game is done

vestal hound
#

ah.

#

in general

#

you can do like a == b == c == d

#

and it will work

#

however, overall

#

this looks like your data model

#

is probably not well thought through

native tide
#

its javascript?

unreal bolt
native tide
#

also i was thinking. nan == nan so sorry

vestal hound
#

it is?

native tide
#

also ignore me then.

#

its js i thought was python

vestal hound
native tide
#

===

vestal hound
#

oh yeah that's not Python

#

I realised

native tide
#

3 equals in js

vestal hound
#

no colon after the if

unreal bolt
vestal hound
#

hold up then what are the parentheses supposed to do

native tide
#

haha im out. its .js ๐Ÿ˜†

vestal hound
#

(item0Inner, item4Inner, item8Inner) == (p, p, p)

native tide
#

use a swtich

vestal hound
#

why do you have parentheses here

native tide
#

delete all that. it was python

vestal hound
#

JS doesn't have tuples

#

also, yes

#

in general

#

you should ask JS questions here only insofar as they are relevant to webdev in Python

unreal bolt
unreal bolt
native tide
#

I'd love to make a website like https://ygg.fun, I've got my own website running now. What's my next step to constructing it, learning HTML?

unreal bolt
#

there is a js discord server or something?

vestal hound
vestal hound
unreal bolt
unreal bolt
native tide
unreal bolt
#

oh okay

native tide
#

Just says Hello There! atm but nothing special at all

vestal hound
#

sorry

unreal bolt
#

so yeah if u dont know html nor css u should go and learn right now (: @native tide

vestal hound
#

like how to build a website (in the sense of the code itself, as opposed to deployment)?

unreal bolt
native tide
vestal hound
#

you could also look into Django

unreal bolt
#

he should go for basic things

#

html + css !

#

no?

vestal hound
#

of course, Flask works too

unreal bolt
#

yeah

#

but

vestal hound
#

but IMO Django is better because

unreal bolt
#

first things first

vestal hound
#

it comes with all the parts

#

that you need for a basic website

#

-> less dependency management

#

shrugs there are many paths

#

this is just one

native tide
#

Say I create a HTML document to structure the main page of my website, how would I get Flask to display that HTML doc?

vestal hound
#

so you need to get the HTML into that response

#

if you want to fill it with data dynamically

#

you'll need a template

#

otherwise, a static HTML will do just fine

fossil pond
wicked sleet
#

I learnt html how do i start learning webdev in python

#

i wanna be a backend one

#

help please

lime mist
#

best way to maintain a server-state in a web server?

This system is made with Python Socket.io and is suppose to load-balance jobs across all available online workers

@sio.event
async def connect(sid, environ):
    server_state.workers_online += 1
    server_state.add_worker(sid)
    await server_state.rebalance_workers(sio)

    log(INFO, f"{sid} Connected!")

    await sio.emit("sid", sid, to=sid)


@sio.event
async def disconnect(sid):
    server_state.workers_online -= 1
    server_state.remove_worker(sid)
    await server_state.rebalance_workers(sio)

    log(INFO, f"{sid} Disconnected!")


@sio.event
async def envoke_workers_rebalance(sid):
    await server_state.rebalance_workers(sio)

The method to note here is server_state.rebalance_workers
and it updates this:

class ServerState:
    def __init__(self) -> None:
        self.workers_online: int = 0
        self.worker_job_maps: list[Worker] = []

here is that method in action:

async def rebalance_workers(self, sio) -> None:
        temp_worker_job_maps: list[Worker] = deepcopy(self.worker_job_maps)

        for worker in temp_worker_job_maps:
            worker.jobs = []
            worker.proxy = None

        proxies = Queue()
        for x in get_proxies():
            proxies.put(x)

        for worker in temp_worker_job_maps:
            if not proxies.empty():
                worker.proxy = proxies.get()

            else:
                break

        active_jobs = Queue()

        for x in get_jobs():
            speed = int(x[2])
            if speed > self.workers_online:
                speed = self.workers_online

            for _ in range(speed):
                active_jobs.put(x)

        while not active_jobs.empty():
            job = active_jobs.get()

            temp_worker_job_maps.sort(key=load_balance)

            for worker in temp_worker_job_maps:
                if job not in worker.jobs and worker.proxy is not None and len(worker.jobs) < MAX_JOB_PER_WORKER:
                    worker.jobs.append(job)
                    break

        self.worker_job_maps = temp_worker_job_maps

While testing I noticed a glitch in worker_job_maps list. I'm speculating it was because this is not the best way to update these variables as some other connect/disconnect/forced_rebalance can evoke this while it might still be getting processed.

What are your thoughts? Is this the right way? If no then how can I make this better?

ionic raft
formal forum
#

Does someone know if it's possible to still use my domain name for mail purposes but make the domain not accessible by going to it with an internet browser?

wicked sleet
ionic raft
# wicked sleet Nooe

I started with Flask in June of this year. Even though I sensed my web project was complex enough, Flask gave me a start to grasp web development (backend, application, front end). After about a month I flipped to Django July 9, 2021. Just under 2 months later and I'm 28k lines of code in. ๐Ÿ™‚ The website I'm building can be found through my profile.

ionic raft
wicked sleet
#

So you means I should start with flask?

ionic raft
# wicked sleet Nooe

For Flask, depending on how you learn:

  • Books are deep, but slower
  • Boot camps should give projects, but not as deep as books (udemy.com)
  • As for tutorials, they're good so long as you continue to delve deeper. I recommend corey schafer on You Tube.
formal forum
ionic raft
ionic raft
ionic raft
# wicked sleet I'll start with it

I LOVE web dev...Seriously. Tons of fun. You get to code in Python and can see the results instantly in the browser. Amazing experience

formal forum
#

Ikr

ionic raft
#

I just built a billing/hour tracker for users in my web app...in less than 24 hours...
I started with tutorials. about 11 apps in the web application later, and I'm starting to get comfortable with Django

#

๐Ÿ™‚ This has two modes...prepaid pool or hourly billing. Determined by the user when they update their profile

#

So yeah...Flask and Django...amazing frameworks. Worth the perseverence.

#

But what amazes me most about Django...is the SPEED of my site. I can only assume that my choice to limit JS on the front end has paid off big time. Ping aside, the click to render speed is astonishing...even when working with DB calls for user data...and on this site, there are DB calls for every page...some of them significant queries.

inland oak
ionic raft
inland oak
#

up to hundreds of times ๐Ÿ˜‰

ionic raft
ionic raft
inland oak
#

I don't like that it mix JS and HTML together

#

I would prefer to try Angular perhaps

#

its structure looks quite prefessional

ionic raft
calm plume
#

It's pretty similar to Jinja2 and the Django template languages, in the sense that it doesn't add much new syntax, it's just a (very very) thin layer on top of regular HTML

inland oak
#

Angular attracts me for looking quite similar to Django structure, battery included approach
and having typescript as mandatory from the start

ionic raft
# inland oak its structure looks quite prefessional

That's encouraging.
My goal is to maintain the rest of the site as-is and ONLY have the JS framework serving up the one app. I've no need for a UI across the site. I just want the diagramming for the one app

calm plume
#

From what I've heard, Angular is losing lots of popularity and satisfaction

inland oak
#

really? too bad.

ionic raft
ionic raft
#

Great website

inland oak
#

huh. interesting

ionic raft
# calm plume Hmm, not that I know of.

That's the kicker...The only reason, for me, to go to a JS front-end is for one specific use case...to build a dedicated diagramming app that can interact with the data that the application layer can send to context in the template.

#

I'm ok with sacrificing speed for that app, but don't want it across the rest of the site

calm plume
#

Ah yeah, if it's diagrams you need, Svelte probably isn't what you want.

#

It's rather new compared to the other more popular frameworks, but it is growing fast.

ionic raft
inland oak
#

I think that's the most rapid technology

#

dissapearing and appearing new ones quite quickly ๐Ÿ˜‰

ionic raft
inland oak
#

well, since I dislike for some reason react

ionic raft
#

React is polling well on that website tho

inland oak
#

I would choose between Vue and Svelte then

calm plume
#

And state management can be hellish

ionic raft
#

Well, thanks for the insights chaps. Still got research to do. May have to explore a few of them. That website is very helpful tho

inland oak
#

I built a simple app with 10 different JavaScript frameworks... Learn the pros and cons of each JS framework before building your next app https://github.com/fireship-io/10-javascript-frameworks

#javascript #webdev #top10

๐Ÿ”— Resources

Full Courses https://fireship.io/courses/
Performance Benchmarks https://github.com/krausest/js-framework-benc...

โ–ถ Play video
#

seeing helloworld in all frameworks quickly)

ionic raft
#

Definitely worth a watch. Ty for sharing

inland oak
#

it does not sound like a way for a big clean project at all

calm plume
#

agreed

inland oak
#

actually it breaks one of clean code principles right from the start ๐Ÿ˜‰

#

Robert Martin recommended to not mix different langs like that

#

liked the book. finally having an image where to go for cleaness

inland oak
#

after looking through video again

#

I think I am bought by svelte

manic crane
#

been getting this error for months =>
django.db.utils.IntegrityError: could not create unique index "Occupy_post_user_id_7dca33ac_uniq"
DETAIL: Key (user_id)=(1) is duplicated.
can someone help please thanks in advacne !

rotund perch
#

I assume u are trying to create a user manually? So u got that error & it tells that the user id already exists

manic crane
#

yh bro but im confused i have no id field ?

rotund perch
#

Django automatically creates an id

manic crane
#

oh wow

rotund perch
#

I suggest to u something if ur input was correct, remigrate all models. That means u have to delete files(except init.py) in the migrations folder in every app and run migrations to start without existing users

#

Or just queryset to delete all users

manic crane
#

i read if delete all files expect init.py it can cause some later errors

rotund perch
#

Ive tried it couple times, but if ur project is sensitive then dont try it + if u want to try it and a bit afraid of errors just backup(do another copy of ur project)

#

But also try this before anything in console :
python manage.py shell

Import User
User.objects.all().delete()

inland oak
#

Angular looks still quite in demand though

#

in terms of job positions

#

equal to React

#

while leaving vue far behind

#

Perhaps it not in satisfaction because of just higher learning curve

native tide
#

hi

#

i need help

#

how do i make a div go to the top left center of my page?

rotund perch
#

Videos or just readable content?

fossil loom
#

Okay but i think i have to know how backend and web developpement work first

calm plume
#

But in terms of the actual framework, I've seen satisfaction decreasing

lime mist
#

best way to maintain a server-state in a web server?

This system is made with Python Socket.io and is suppose to load-balance jobs across all available online workers

@sio.event
async def connect(sid, environ):
    server_state.workers_online += 1
    server_state.add_worker(sid)
    await server_state.rebalance_workers(sio)

    log(INFO, f"{sid} Connected!")

    await sio.emit("sid", sid, to=sid)


@sio.event
async def disconnect(sid):
    server_state.workers_online -= 1
    server_state.remove_worker(sid)
    await server_state.rebalance_workers(sio)

    log(INFO, f"{sid} Disconnected!")


@sio.event
async def envoke_workers_rebalance(sid):
    await server_state.rebalance_workers(sio)

The method to note here is server_state.rebalance_workers
and it updates this:

class ServerState:
    def __init__(self) -> None:
        self.workers_online: int = 0
        self.worker_job_maps: list[Worker] = []

here is that method in action:

async def rebalance_workers(self, sio) -> None:
        temp_worker_job_maps: list[Worker] = deepcopy(self.worker_job_maps)

        for worker in temp_worker_job_maps:
            worker.jobs = []
            worker.proxy = None

        proxies = Queue()
        for x in get_proxies():
            proxies.put(x)

        for worker in temp_worker_job_maps:
            if not proxies.empty():
                worker.proxy = proxies.get()

            else:
                break

        active_jobs = Queue()

        for x in get_jobs():
            speed = int(x[2])
            if speed > self.workers_online:
                speed = self.workers_online

            for _ in range(speed):
                active_jobs.put(x)

        while not active_jobs.empty():
            job = active_jobs.get()

            temp_worker_job_maps.sort(key=load_balance)

            for worker in temp_worker_job_maps:
                if job not in worker.jobs and worker.proxy is not None and len(worker.jobs) < MAX_JOB_PER_WORKER:
                    worker.jobs.append(job)
                    break

        self.worker_job_maps = temp_worker_job_maps

While testing I noticed a glitch in worker_job_maps list. I'm speculating it was because this is not the best way to update these variables as some other connect/disconnect/forced_rebalance can evoke this while it might still be getting processed.

What are your thoughts? Is this the right way? If no then how can I make this better?

rotund perch
#

Did anyone tried doing an API with django and showing response data with TEMPLATES at the same time. Ive tried that and I think its a good way if u dont want to use a frontend framework and want to implement an API. So does it include any later problems ive not notice? performance & speed? more querysets? less secure? etc..

NOTE: Doing this needs to have atleast 2 views, one for the API View, and the other is for the TEMPLATE View, same for URLs.

wind dove
#

I'm creating a Django app which is basically a social media app. On the social media app you can upload images, how should I go about storing these images on the server? Should I just write the image to a file, should I encode it to b64 and put in in the database or something else?

#

if someone replies please @ me

wind dove
#

For production

rotund perch
#

do u know how to host files?

#

u need to host ur files with a host provider

wind dove
#

Not yet, I'm still learning a lot of this

rotund perch
#

okay, so I think u will need to learn hosting files first and then get into showing images in ur django app

wind dove
rotund perch
#

images are stored in the host cloud

wind dove
#

Alright

#

Thank you, I'll look into it!

rotund perch
#

np

ionic raft
ionic raft
# wind dove I'm creating a Django app which is basically a social media app. On the social m...

@wind dove I made the decision to stay away from uploaded media in production. Storing media on the app server loses statelessness of Django, and hinders load balancing potential. Storing to the DB presents security risks. I have opted to use external image hosting when needed down the line. For now, I upload images for articles (blog) as a static image behind the scenes and collectstatic inside the docker container.

ionic raft
rotund perch
ionic raft
rotund perch
ionic raft
rotund perch
ionic raft
#

In other words, if a image hoster is trustworthy and has the resources to scale, why re-invent that wheel? Unless of course, you want to become an image hoster yourself

rotund perch
#

Yes Awesome ,Thanks.

fossil pond
#

Hey good people! I want to add a radio button to my Django form and I was thinking how do I introduce that variable to my model class?

#

Any help is appreciated

lime mist
#

Can uvicorn serve 2 instances of a same web app to 2 connected clients?

I am using uvicorn to serve my socket.io server using heroku and there one of the things I'm maintain is an online users variable. I connected 2 clients which they did successful it still shows 1 as online users.

The code is perfect as if works fine when I test it on localhost. So my speculation is that uvicorn is somehow serving 2 instances of my server.

Can this be true? If yes then how can I disable it?

bitter hamlet
#

hello guys. I am pretty new to this area and I have to make a site to my school project in such a small period of time. Well, I was trying to use materialize css to do a Tab feature and I managed to do this, but I don't know how to align the iframes the way I'd like to. I'll show a pic of how (at least close) it should be

gusty verge
#

sorry buddy but i don't know

ionic raft
#

@fossil pond I've made use of the select input to great effect on a filter for lists on my Django site...

rotund perch
#

Anyway for counting requests or responses or queries per action in django?

cerulean badge
#

can you filter with model method with django_filter library?
or do i need to write my own logic in a function?

ionic raft
hearty tendon
#

So, I can use Object.values(msg.var_name)

rotund perch
cerulean badge
#

i have a order model when someone order on cod but the address is wrong (we can't validate if its wrong) what flag to set on the order?
any recommendation. its a personal project

desert cradle
#

Please tell me how to refer to the specific index of the list in the template of django.

#

ex){{ user[location].name }}

#

how to use this in django?

vestal hound
stuck trellis
lusty wigeon
#

I need to implement an dropdown with each option I want separate form.. For example i have 1 form which has dropdown type1 2 3 and I want for type 1 enabled separate form 1, for type2 dropdown option it enables form2 and so on dynamically...

#

Django...

lusty wigeon
#

found it with keyword "dependent" fields...

night lynx
#

Anyone know how to fix 1020 cloud flare error?

#

It comes from reqeusts calls

wicked sleet
#

any free flask course to get started

#

help

wicked sleet
#

thanks

desert estuary
#

i setted up the app debug to true still ending up on production

native tide
cerulean badge
#

can this be simplified further?

def clean(self):
        if not self.placed:
            if self.paid:
                raise ValidationError(
                    "Order can't be paid if its not placed"
                )
            if self.dispatched:
                raise ValidationError(
                    "Order can't be dispatched if its not placed"
                )
            if self.rejected:
                raise ValidationError(
                    "Order can't be rejected if its not placed"
                )
        if not self.dispatched and self.delivered:
            raise ValidationError(
                "Order can't be delivered if its not dispatched"
            )
        if self.paid and self.rejected:
            raise ValidationError(
                "Order can't be rejected if its paid"
            )
        if not self.rejected and self.reject_reason:
            raise ValidationError(
                "Order can't have reject reason if its not rejected"
            )```
desert estuary
cerulean badge
#

(context django) if i have textfield with blank=True do i need to provide default?
or does it have empty string if no value is provided?

eternal blade
#

blank is if the value can be empty in Forms

#

you will have to supply a value for it if the field is not nullable

slim vigil
#

got a quick question

#

@ me if anybody can help or give some advice

#

basically

#

im working on a game rn

#

a text based RPG

#

that's just text only

#

and i wanna put this on a website

#

as opposed to like a downloadable exe that runs in the terminal (the way i currently have it)

#

and what's the easiest way to go about this

#

im a total beginner with python webdev

#

actually nevermind

#

ignore that

signal nova
robust wolf
#

Anyone know where to find beginner friendly tutorial for Django?

native tide
#

Hi, im trying to make a simple endpoint @upbeat sigil_view(['GET']) that returns a string, does this look correct?

#
def simpleEndpoint(request):
    return Response("Hello world")```
#

or should i just return "Hello world"?

#

so just removing Response

#

And how can I test if this works?

rotund perch
#

Its correct, if u want to test it u can either use postman or a browser

#

Just do a url that points to that function to call it, and write the url in the browser

native tide
#

Sweet

#

Thank you ๐Ÿ™‚

rotund perch
#

Np

fossil pond
#

Hey guys! For my Django routing it goes to R:\Projects\Websites\project\main\static\images\ when it should not go to static idk why that's happening. Has anyone faced this issue?

cedar flax
#

hey guys ! i have a question. now when developing apps with kivy, or desktop apps with tkinter (or something else), orr even websites with django+flask. am i able to design first in figma or adobexd and then convert those files to the code ? or how does it work ? because for example .. most of kivy apps look ugly, soo designing them with figma in my opinion is better and then transferring them to the code. is that possible ?

mystic wyvern
fossil pond
#

I fixed it by changing the redirect link from href ="/contact" to href="{% url 'contact' %}"

#

But strange because for my other pages href ="/resource_name" is working fine

#

Would love to know why it happened

mystic wyvern
fossil pond
mystic wyvern
#

@fossil pond
can you plz show me your urls file

native tide
#

someone know why the fontawesome stuff is only working once?

#

i used the links on differtent html file but it only works on one

mystic wyvern
native tide
#

ah i forgot to do this on every site:
<script src="h ttps://ki t.fontawesome .com/5136008 754.js" crossorigin="anonymous"></script>

native tide
#

how can i change the size of a container with flexbox?

fossil pond
#
    path("", views.home, name="home"),
    path("projects/", views.projects, name="projects"),
    path("project/<str:pk>/", views.project, name="project"),
    path("portfolio/", views.portfolio, name="portfolio"),
    path("inbox/", views.inbox, name="inbox"),
    path("contact/", views.contact, name="contact"),
    path("message/<str:pk>/", views.message, name="message"),
]```
mystic wyvern
#

Did you try adding a backslash like I told you?

#

dude can you show me what the error when you want to redirect

#

is it page not found ?

ionic raft
ionic raft
# fossil pond Would love to know why it happened

Including static at the template start combined with {% static url 'url-name-here' %} is the guaranteed way for it working. If not calling static worked for another page , I'd be curious to see url.py for the app, along with the template html. However, understanding why it worked using the incorrect approach is probably not as helpful as understanding the correct way to call on urls within Django. I hope that makes sense. ๐Ÿ™‚

native tide
ionic raft
fossil pond
ionic raft
fossil pond
# ionic raft Including static at the template start combined with `{% static url 'url-name-he...

urls.py:

from django.urls import path
from . import views

urlpatterns = [
path("", views.home, name="home"),
path("projects/", views.projects, name="projects"),
path("project/str:pk/", views.project, name="project"),
path("portfolio/", views.portfolio, name="portfolio"),
path("inbox/", views.inbox, name="inbox"),
path("contact/", views.contact, name="contact"),
path("message/str:pk/", views.message, name="message"),
]

and for the template even if it is blank I get the same output so I doubt it is relevant. But thank you, I shall use the correct way. A few bad tutorials can really ruin a lot of hours!

ionic raft
# cedar flax hey guys ! i have a question. now when developing apps with kivy, or desktop app...

Not being familiar with figma I can't say anything in that regard. However, as someone who started learning Django recently, I'd suggest that developing code within the Django application layer (views.py for the app) or Flask is something that is best from within Django. There are a number of reasons for this, but explaining them if you don't know Flask or Django could quickly get confusing.

The idea of trying to port Python into a Django app doesn't strike me as an intuitive approach. Django/Flask is a framework that offers a way of building a web application with a spectrum of potential. But then, the use case of what your code is trying to accomplish would have a bearing on this. Most Django python code I've worked with is mostly about CRUD with the DB, and building the interface with the front-end (the browser). What I like about web applications is that once I'm clear on html/css (and even JS if I feel I need more dynamic behaviour) I've got the question of UI addressed.

ionic raft
# fossil pond urls.py: from django.urls import path from . import views urlpatterns = [ ...

Yes...a bad tutorial can be BRUTAL. I feel your pain. That said, it is good to be on the other side. Ultimately, once you get including static, along with how the urls.py files work for each app, you'll find it all making more sense. I'm currently working on an web app that has 11 applications and likely more than 200 urls. Naming those urls intelligently so that it's super clear what you're working with gets more important as the web app scales. Also, using an IDE that will auto-populate can be a time saver like you wouldn't believe.

ionic raft
native tide
#

not yet, im working my way up to django currently by learing css, squlite and js haha

ionic raft
native tide
#

still a long way

#

but do you know how i can reduce the size of a container with flexbox?

#

id like to shrink down the site a bit

#

i think its currently scaling with the desktop resolution size so no size limit

ionic raft
#

I have been using bootstrap, which comes with flex embedded. I typically manage flexbox by setting up as follows


            <div class="row">
                <div class="col-2">
                    <h5>Customer</h5>
                </div>
                <div class="col-2">
                    <h5>Type</h5>
                </div>
                <div class="col-2">
                    <h5>Scope</h5>
                </div>
                <div class="col-4">
                    <h5>Need</h5>
                </div>
                <div class="col-2">
                    <h5>Rank</h5>
                </div>
            </div>```
What the above shows is a row with 5 columns. Each row can be divided into 12 columns. I happen to have cols with 2-2-2-4-2 (which totals adds to 12).
Now, if image size is an issue, you might look at capping the width of the image by setting a width with css for the image and applying that class.
native tide
ionic raft
#

In turn, in subsequent rows I start again, and can declare a col structure that is the same or different. It feels intuitive now that I've been using it for a couple of months, and comes down to thinking...each row can have upto 12 columns....

native tide
#

i fear that when i switch to bootstrap one day that my whole grid system is doomed xD

ionic raft
native tide
#

๐Ÿ˜„

ionic raft
#

but then, I didn't start coding with Python to become a css master ๐Ÿ˜„

#

I needed enough css to get a UI that works for me and looks decent.

native tide
#

tkinter works also for UI but yea css is simple and has more fancy features ๐Ÿ˜„

#

but im still a beginner with html, css etc so bootstrap is kinda like a game mod, modding/adjusting the code/features itself?

ionic raft
ionic raft
# native tide but im still a beginner with html, css etc so bootstrap is kinda like a game mod...

Bootstrap/Tailwind is an easy vector into styling. They're taken care of a lot of the things you're most likely to need. They're also proven and tested, so for the majority of UI demands they're a rapid way of getting a build. I wanted my web app project to expand in functionality and have a consistent UI. Bootstrap gave me a quick way to establish a UI I liked. And I still like 11 applications later in Django.
That said, there's also the JS Framework route...which takes UI and behaviour to whole other level.
All said and done, I'm happy with my start with Bootstrap. For the next project I'll try Tailwinds for the experience.

#

And then one day, when I've got the time I'll delve deeper into css. However, a css Framework introduces you without requiring you to understand it all.

native tide
#

so it makes things simpler compared to vanilla css?

ionic raft
# native tide so it makes things simpler compared to vanilla css?

Simpler. Hands down. There's a learning curve. However, there's also great documentation.
I started by querying how to "do something with bootstrap/tailwinds stack overflow" and someone had the answer already out there.
Bootstrap allowed me to move quickly into focusing on function, with the comfort that form/style is great. My css file is 650 lines, and it's been weeks since I touched it.

#

I hear great things about Tailwinds though. So either flavour comes well used and regarded

native tide
#

alright i will take a look into it but i really fear it just ruins my whole project xD

fossil pond
#

Has anyone here used crispy forms? I want to make a really cool looking contact form with it. It has bootstrap integration. Can you share some good resource if you have?

ionic raft
ionic raft
fossil pond
#

Sorry xD

#

If you have any resources please share them now Iโ€™ll look at them when I wake up

ionic raft
desert cradle
#

How do you implement this in html?
list_var[index].option

ionic raft
desert cradle
ionic raft
#

So, you're using jinja2 for templating.
Are you using class based or functional view in views.py?

desert cradle
#

umm..I dont know..I used function.

ionic raft
#

the context dictionary is going to look something like:py context = { 'year': get_current_year() }

Once the context dictionary is built, then you can call on that in the html template:

{{ year }}```
desert cradle
#

I received data from DB and handed over the list information to context. But I want to refer to a specific index value within html, but I can't.

ionic raft
#

If you pass over a list, then in the template you can use a for loop in the template: ```html
{% for element in list %}

Html

{{ element }}
{% endfor %}```
The for loop in jinja feels just like a for loop in python. This can extend to dictionaries as well.

desert cradle
#

Thank you. I got it.

ionic raft
#

Looping inside html allows you to amazing stuff. Good luck ๐Ÿ™‚

#

{% load index %} in jinja can be done too. You can import index into a template, and then use the {{ element|index:forloop.counter0 }} tag to manage multiple lists within a for loop.
If you use index though, you need to import a package for that.

desert cradle
#

There's one more question. If i receive the variable 'location' in the first for loop, how do i refer to the 'location' of the list?
ex)in Python
for location in var: list[location].option

#

'location' is list.

ionic raft
desert cradle
ionic raft
ionic raft
inland oak
#

Svelte looked just so attractive to me, quite interesting to choose, but needing to know if there will be not problems with essential libraries

#

Or better to go safer vue.js

#

I think vue.js would be safer for startup purposes

#

svelte looks like lightweight solution for pet projects at the moment

opaque rivet
#

Why not React? Nice and simple and it's the new craze.

inland oak
#

check how Svelte looks clean

wide canyon
#

Hello

opaque rivet
#

Looks cool. I'd probably learn Svelte over React but I'm way too far into it now and the job prospects are the best. Looks good tho.

#

Might not be as many community libraries to use though.

wide canyon
#

I wrote an article for real time chat. I used the header to pass the token for token authentication. Im working with a frontend developer now and i was told it's impossible to pass custom headers for wbsockets through js. I have to change the middle ware to make it take token through query parameters. Ive done that. But I'd like to know if there's a way to pass custom headers for ws requests

inland oak
#

for my pet projects, I would definitely go Svelte though

dusk portal
#

hey @ionic raft

tawny pollen
#
(blog) C:\Users\Yong PC\Documents\try_django\blog\try_django>py -m pip install django
Requirement already satisfied: django in c:\users\yong pc\appdata\local\programs\python\python39\lib\site-packages (3.2.7)
Requirement already satisfied: asgiref<4,>=3.3.2 in c:\users\yong pc\appdata\local\programs\python\python39\lib\site-packages (from django) (3.4.1)
Requirement already satisfied: sqlparse>=0.2.2 in c:\users\yong pc\appdata\local\programs\python\python39\lib\site-packages (from django) (0.4.1)
Requirement already satisfied: pytz in c:\users\yong pc\appdata\local\programs\python\python39\lib\site-packages (from django) (2021.1)
WARNING: You are using pip version 21.1.3; however, version 21.2.4 is available.
You should consider upgrading via the 'C:\Users\Yong PC\AppData\Local\Programs\Python\Python39\python.exe -m pip install --upgrade pip' command.

(blog) C:\Users\Yong PC\Documents\try_django\blog\try_django>django-admin
'django-admin' is not recognized as an internal or external command,
operable program or batch file.
``` why is django-admin not working?
thin lance
# tawny pollen ```py (blog) C:\Users\Yong PC\Documents\try_django\blog\try_django>py -m pip ins...
[auth]
    changepassword
    createsuperuser

[contenttypes]
    remove_stale_contenttypes

[django]
    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    makemigrations
    migrate
    sendtestemail
    shell
    showmigrations
    sqlflush
    sqlmigrate
    sqlsequencereset
    squashmigrations
    startapp
    startproject
    test
    testserver

[sessions]
    clearsessions

[staticfiles]
    collectstatic
    findstatic
    runserver


commands

#
python3 manage.py findstatic --version

I'm not sure about env but this is the way to work with a docker and a docker-container,
i don't believe there is any big difference in commands.

calm plume
calm plume
#

If you do that, then it should fix itself

inland oak
#

typescript is supported by svelte too

#

what else to wish?

#

I'll take svelte for myself ;b

dusk portal
#

i wanna give user a add to cart /bag option how can i do that

#

@ionic raft

opaque rivet
#

@inland oak pretty sure TS is supported by all the major frameworks.

inland oak
#

it started to support TS only in 2020 year

#

well, svelte appeared only in 2019 year

quick cargo
#

Svelte is very nic3

inland oak
quick cargo
#

The lack of a virtual dom runtime also makes it probably the go to if you want browser support

#

Its the only frameworm I've used that supports my ipad with safari that hasnt bren updated in 6 years

#

Previous mostly worked with vue or react

inland oak
#

if you would be limited only to them

quick cargo
#

Svelte 100%

inland oak
#

except svelte? ๐Ÿ˜‰

quick cargo
#

After working with it for a while its definitely my favourite framework

#

After that probably vue

#

Generally i prefer the template layout svelte and vue

inland oak
#

thanks. interesting.

#

a bit curious how would some dev compare his experience with angular too

#

eh, if only I had a bit more time to learn frontend ๐Ÿค” it would be nice to play with svelte

#

but I am bit too busy learning devops stuff

native tide
#

window.redraw = function( _id, endpoint ){
$.get( endpoint, function( data ) {
$( "#"+_id ).html( $(data).html() );
});
}

#

a method that just redraws returned html to the dom is also cool.

#

and just use python

manic crane
desert estuary
#

idk whats going on isn't this how u start a virtualenv

desert estuary
#

i guess this is more of a python prob cuz im working on flask and i had this project on windows now since i shifted to linux idk howo to do so
should i still go to #editors-ides

tiny snow
#

Well it's definitely not a web dev problem

dusty urchin
#

Does anyone know how I can split files and make them use the same imports without writing it on top of each file separately?
Basically I want to do all my imports once (like general imports) for a bunch of files to avoid redundancy of the code.

rotund perch
manic crane
#

okay so my best chance is to delete all files expect init.py

manic crane
rotund perch
#

np

thin lance
dusty urchin
thin lance
#

I don't think that's possible

dusty urchin
#

Me neither after thinking about it for longer

thorny quartz
#

I am getting this error

#

Unknown field(s) (username) specified for User. Check fields/fieldsets/exclude attributes of class AccountAdmin.

#

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import *
from .forms import RegistrationForm

class AccountAdmin(UserAdmin):
add_form = RegistrationForm
list_display = ('email', 'first_name', 'date_joined', 'last_login', 'is_active')
search_fields = ('email',)
readonly_fields = ('id','date_joined', 'last_login')
ordering = ('email',)

filter_horizontal = ()
list_filter = ()
fieldsets = ()

admin.site.register(User, AccountAdmin)

admin.site.register(Category)
admin.site.register(Product)

#

anyone please help

jovial cloud
topaz finch
#

So I want to have 2 webservers running on the same machine. If I purchase an additional IP for that machine, then simply set the host to the desired IP for that server, would that be all I need to do, or would more configuration be required?
Please ping me when responding

inland oak
#

with a bit of nginx rules you could setup...

#

if requests start with /somepath, then they go to first web server

topaz finch
#

I am running Apache on this server btw

inland oak
#

if with / path, then to second server

topaz finch
#

Am I able to do it by subdomain?

inland oak
#

well yeah, it could be used too

#

But!

#

better just deploying to two servers ;b

#

what do you deploy?

topaz finch
#

Right now I have 3 servers for 3 different webapps, but I figure if I can just stop purchasing more servers that would be good. I am going to add a webserver to a Discord bot in the same application, aiohttp

brave stag
#

how to test Django signal 'user_logged_in'?

fossil pond
#

Hi guys! I'm having a problem with a multiple type checkbox that I've implemented using crispy forms on Django. I get an error saying that they are not the right fields when a user chooses them.

project_type = models.CharField(max_length=20, null=True, choices=TYPE) : models.py
project_type = forms.ChoiceField(choices=TYPE, widget=forms.CheckboxSelectMultiple) : forms.py

What mistake did I make?

#

TYPE = [ ('mobile', 'Mobile'), ('desktop', 'Desktop'), ('web', 'Web'), ('other', 'other'), ]

#

It appears in the UI but when someone chooses 1 or more values , a JS prompt is received saying that the fields aren't right

topaz finch
inland oak
#

describe a bit

brave stag
# brave stag how to test Django signal 'user_logged_in'?

I'm implementing the user login activity
so when the user logs in It fires a signal which creates an entry in a table
but while testing the login with the client it also fires the signal and the signal is expecting a request

Need help in this guys

topaz finch
#

I have a Discord bot, and I want to set up a subdomain for it, so that it has its own small website. I am deploying the Discord bot and webserver in the same application.

inland oak
#

you could be forced to have one server though

#

depending on how you will choose exporting data

#

bot could be having some backend tied to it anyway

#

but web server could be on a separate server anyway

topaz finch
#

Im running the bot and aiohttp server in the same application, so I wont really need to export data

#

Ill look into getting another server, thanks for the advice

#

I will probably just do development on my main server on a port for now

queen granite
#

guys i need a html help
i am deploying a ml model
but when i hit predict the textbox values are resetting
when i tried to fix that result is not coming

#

i tried onsubmit = "return false"

#
<div class="login" onsubmit="return false">
    <center><h1>Surge Price Prediction</h1></center>
  <center>  
     <!-- Main Input For Receiving Query to our ML -->
    <form class="form" id="Formid" action="{{ url_for('predict')}}"method="post" >
      <label for="Type_of_cab">Type_of_cab:</label><br>      
      <select name="Type_of_cab" id="Type_of_cab"></br>
              <option value=" "> </option>
              <option value="0">A</option>
              <option value="1">B</option>
              <option value="2">C</option>
              <option value="3">D</option>
              <option value="4">E</option>
      </select><br>
            <br>
            <label for="Gender">Gender:</label><br>      
      <select name="Gender" id="Type_of_cab"></br>
              <option value=" "> </option>
              <option value="1">Male</option>
              <option value="0">Female</option>
      </select><br>
      <br>
      <br>
      <label>Confidence_Life_Style_Index</label><br>   
       <select name="Confidence_Life_Style_Index" id="Confidence_Life_Style_Index"></br>
        <option value=" "> </option>
        <option value="0">A</option>
        <option value="1">B</option>
        <option value="2">C</option>
       </select><br>
      <br>
        <button type="submit"  class="btn btn-primary btn-block btn-large">Predict</button>
        <br>
    </form>
 </div>
graceful flax
#

Hey is it good practice to format all my data using serializers in django?

sonic island
#

"REST framework also introduces a Response object, which is a type of TemplateResponse that takes unrendered content and uses content negotiation to determine the correct content type to return to the client."
what's unrendered content means here?

uncut parcel
#

is this the place to talk about low level web stuff?

#

like im talking tcp packet level

flint wasp
#

u hv made this using

native tide
#

tkinter

flint wasp
#

@native tide

native tide
#

yes

#

?

flint wasp
#

ooh nicely built

native tide
#

ty lol

#

it was my first ever tkinter projects

#

and my last

#

i dont use tkinter any more

#

it isnt too good tho

flint wasp
#

meanwhile im stuck with this

native tide
#

lacks features

#

What are u stuck with

timber cloak
flint wasp
#

so it comes like this

#

center of fram

#

e

native tide
native tide
#

wym

#

html css js

flint wasp
#

oh i dont know that yet

native tide
#

i just started learning it

#

i hate css so much

flint wasp
#

stuck on vsc

flint wasp
native tide
#

its just annoying

#

confusing

flint wasp
#

ok

flint wasp
timber cloak
flint wasp
#

fill x

#

whats pad

native tide
#

im no good with design sorry

#

thats why i hate css

timber cloak
#

padding

flint wasp
#

ok

#

how to get above return button

#

thats what i want

#

@timber cloak ?

timber cloak
flint wasp
#

i hv done that

#

the label and entry widget are a single func instantiated before the return button

timber cloak
flint wasp
#

nvm i shall ask tmrw

timber cloak
flint wasp
#

its 12 here

#

bye gn

timber cloak
#

oh ok

ember eagle
#

heyo... hopefully quick question... i have two database columns, one that lists a member of a server and another that lists roles associated with that member on that server... when trying to "display" those roles, i run into a (very long executing) template display challenge. i think it may be a custom filter thing but i'm not opposed to rearranging data also... any thoughts on how to simplify this?

{% for role in roles %}
  {% if role.memberServerID.id == member.id %}
    {{ role.roleID.name }},
  {% endif %}
{% endfor %}```
desert cradle
#

Does raw query and ORM have the same model?

lunar matrix
#

how can I speed up a flask view that is making a call to an external API?

#
@app.route('/loading')
def loading():
    assignments: dict[str] = dict()
    global courses_list
    if len(courses_list) == 0:
        courses_list = get_courses(session)
    for course in courses_list:
        assignments[course.orgunit_id] = get_assignments(session, course.orgunit_id)
    return render_template("courses.html", courses=courses_list, assignments=assignments)
#

im assuming the best solution is implementing a docker container that uses celery and redis

#

but idk where to start with that, never used either

topaz finch
#

How do I go about setting up a quick email server? Not looking to do anything fancy, just send an email

#

Please @ me when responding

lunar matrix
#

dunno if this helps at all

#
from flask import Flask
from flask_mail import Mail

app = Flask(app_name)

app.config['MAIL_SERVER']='smtp.mailtrap.io'
app.config['MAIL_PORT'] = 2525
app.config['MAIL_USERNAME'] = '97e041d5e367c7'
app.config['MAIL_PASSWORD'] = 'cfaf5b99f8bafb'
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False
mail = Mail(app)

@app.route("/")
def index():
  msg = Message('Hello from the other side!', sender =   'peter@mailtrap.io', recipients = ['paul@mailtrap.io'])
  msg.body = "Hey Paul, sending you this email from my Flask app, lmk if it works"
  mail.send(msg)
  return "Message sent!"

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

Im currently using SendGrid, but 100 free emails a day is about to be too few. Am I able to retain my domain as the domain for the email?

frosty cedar
#

@topaz finch is it a domain you bought? like your own .com/whatever top-level domain?

frosty cedar
#

@topaz finch you should be able to move your MX/SPF records to whatever email provider you choose then

topaz finch
#

Most dont seem to have good enough free plans, and I am not looking at paying more than a few bucks. Thats why I am trying to figure out how to set this up with my own VPS servers

frosty cedar
#

@topaz finch there is a lot to consider with hosting your own email. standing it up, securing it from attacks, privacy/data retention. not to dissuade you, but I would vet pricing from other providers before taking it on yourself.

topaz finch
#

Fair enough, any suggestions as to who? I mean, I would be fine with sendgrid if they didnt go from free to $15

frosty cedar
#

while I hate to pitch Amazon, they'll give you 62k emails per month under their free tier for SES

#

@topaz finch mailgun has a flexible, "pay-as-you-go" offering

topaz finch
#

Awesome, I will check both out. Thanks so much @frosty cedar

frosty cedar
#

@topaz finch you're welcome!

dense slate
#

In Django+React (with jwt tokens), I found a weird effect that when I login through my site (react), it gives me a JWT token as expected but also creates a session cookie. When I go to log out through the client and then log back in as another user, it logs me back in as the same user as before.

I get the feeling that the session is what's still active and being authenticated but I'm not quite sure what part of the auth process the hiccup is in. Anyone seen this before?

runic lodge
#

What would be the best direct route to building a drag and drop front end UI?
Django, flask? Frameworks?

ionic raft
tawny pollen
#

django newbie here. i have a question:

Django uses an Object-Relational-Mapper (ORM) to map model definitions in the Django code to the data structure used by the underlying database. 
``` what does "map model definitions" mean ?
native tide
#

Hello?

buoyant geode
#

Hi Im trying to create virtual env using pipenv install django and i get this error please help ValueError: Unable to find resource t64.exe in package distlib

native tide
#

Hey raghava

#

Do you know how to use selinium

buoyant geode
#

I dont know I am new to web development I think might help you https://www.geeksforgeeks.org/selenium-python-tutorial/

opaque rivet
#

@tawny pollen To be able to interact with a database, you have to do so with SQL. The django ORM maps your pythonic code into SQL. e.g. writing a model then migrating will create a table in the database.

fast lava
#

Is anybody here

#

pls help me

#

im using flask

opaque rivet
#

@runic lodge Django/ Flask acting as APIs. More importantly is the frontend framework. I've had simple drag and drops with React. It gets pretty complex. Look at react-beautiful-dnd.

vestal hound
fast lava
#

ok

inland oak
runic lodge
#

How does the api for flask work?
I know python would be for backend, breaking down code, running algos etc. and whatnot but what about that mid level stuff

opaque rivet
#

@runic lodge wouldn't call it a pipeline. But yes.

inland oak
#

Svelte can work for frontend too

rotund perch
#

Hello, Whats the Diff Between JWT & Knox Auth In Django. Also, Which is Better for Security Purposes

celest lodge
#

any web ideas

thin lance
thin lance
#

Help django class based view
template:

<form action="{% url 'search' name=contact_list.first %}" method="GET">
  {% csrf_token %}
  <input type="search",name="search", placeholder="Search contact", aria-label="Search">
  <button type="submit", class="btn btn-success">Search</button>
</form>

view

class SearchContact(ListView):
    model = AdressEntery
    template_name = "main/search.html"
    context_object_name = "src"
    def get_queryset(self, *args, **kwargs):
        queryset = super(SearchContact, self).get_queryset()
        search = self.request.GET.get('search')
        queryset.filter(name__startwith=self.kwargs['name']) #it should be here queryset.filter(name__startwith=search)
        return queryset

the problem is that my self.request.GET.get ('search') returns None

velvet yew
#

I've got an api/views.py that goes like this:

from functions import connect_mongodb
mongo_client, db = connect_mongodb()

And a functions.py like this:

def connect_mongodb():
    mongo_client = pymongo.MongoClient(f"mongodb+srv://{MONGODB_PATH}")
    db = mongo_client["django"]
    if DEBUG:
        print(f"Connected to MongoDB ({__name__})")
    return mongo_client, db

When api/views.py starts it prints Connected to MongoDB (functions) since connect_mongodb() is imported from functions.py. How can I change it so it prints Connected to MongoDB (api.views) like if I were to print __name__ in api/views.py (that returns api.views) but still keep the function imported?

desert estuary
#

so i made this database in flask_sqlalchemy

#

and i can't access it

chilly falcon
#

in django model what will be relation between stock and order-item on_delete = models.CASCADE or on_delete = models.PROTECT

#

or any other