#web-development

2 messages ยท Page 117 of 1

hushed barn
#

@toxic flame So should i just start a new project and quit this 1 because no 1 can figure it out

native tide
#

only 10... wow

#

@hushed barn maybe change what your view returns

#

and does your console say anything?

hushed barn
#

but if i cant even open an empty page

#

console says nuthing

#

it worked yesterday but doesnt work anymore i didnt do anything

steady maple
#

if ur 10 u cant be on discord

native tide
#

this ain't the place...

hushed barn
#

yes well i can be with a guardians permission and if i am mature enough

steady maple
#

oh ok

native tide
#

@hushed barn and the other routes work fine?

hushed barn
#

Yea but the from products.views import* does nothing to my code

#

unused imposrt statement

native tide
#

you don't need that.

from products.views import * imports everything form products.views, but in your products app you import them anyway

hushed barn
#

done

#

But could it be something to do with my firewall?

#

maybe a runserver command

slim beacon
#

firewall wouldnt stop you from connecting locally i think

hushed barn
#

yea true but maybeee ya know

native tide
#

well, I think it points to something external blocking it. Nothing shows in the console, and the routes look right

#

@hushed barn Can you send us a picture of your console

#

The "run" tab in pycharm

hushed barn
#

hey can you join a channel ill scweenshawe

#

oh it dont work

native tide
#

simpler to just send a screenshot of the run tab

hushed barn
#

oh what the fuck

native tide
#

well... there's your answer... since you ran into an error the server stops and when you retry the connection the server isn't running so it refuses to connect

hushed barn
#

so how do i fix that

#

i need to define enviroment?

native tide
#

I've never ran into that problem so idk

#

give it a search

hushed barn
#

yea well thanks a lot tryna fix this up

blazing sapphire
#

am i doing something wrong here. it just doesnt get redirected to the home route

  res.sendFile(__dirname + '/client/test.html');
});

app.post('/test', function (req, res) {
  setTimeout(function () {
    res.redirect('/')
  }, 5000)
})```
native tide
#

@blazing sapphire what if you specify the function in setTimeout outside of that block, then reference it inside setTimeout? I don't know whether that's the right usage of it.

blazing sapphire
#

even if i remove setTimeout, it still doesnt work

native tide
#

@blazing sapphire are you using react?

blazing sapphire
#

no

hushed barn
#

@native tide im dying here why does this show errors im doing it exactly like i read the page

native tide
#

read the error on the side, hover over the red for the error

#

you need a comma on the products path

#

because its a list

hushed barn
#

ok thanks

native tide
#

hey guys I just learned the basics of flask by watching a 1hr video by FreeCodeCamp
i'm confused what should I do now?

#

what projects should I make?

#

I tried googling but still confused lol

#

help

rustic pebble
#

make a covid cases tracker

#

@native tide

native tide
#

๐Ÿค”

#

how? lemon_sweat

#

@rustic pebble

rustic pebble
#

Figure it out

#

Lol

#

Its a project

native tide
#

ok

#

so I can a covid tracker with python like this (or some other way) and deploy it using flask and heroku? @rustic pebble

rustic pebble
#

Yes

native tide
#

thanks for the help

#

I will try to figure out th rest on my own

rustic pebble
#

alright

#

good luck

native tide
#

and is that code the only way to make a covid tracker?

rustic pebble
#

No

native tide
#

I want to do something by myself and not copy the code

rustic pebble
#

You can create your own wrapper

native tide
#

wrappers = decorators?

rustic pebble
#

No

#

You can make a background job that checks this folder:

#

Every day

#

And updates a database with all countries

native tide
#

๐Ÿค”

#

ok

rustic pebble
#

Or you can just increment the day by 1 in this url

#
https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_covid_19_daily_reports/11-24-2020.csv
#

It is CSV so parsing it is easy

native tide
#

oh

#

it is called web scraping?

#

with bs4 and other libraries

rustic pebble
#

Its not rly scraping since you have direct access to the file

native tide
#

oh

rustic pebble
#

All you need is the raw

#

So basically this link

https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/11-24-2020.csv
#

A simple request would do it

#
data = requests.get(f'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/{current_month}-{current_day}-{current_year}.csv').text
#

As simple as that

native tide
#

oh

#

I get it

#

so I have to parse the repo and check for new files daily (for which I can write an automated script? or smth? idk)
then I can make a flask application that displays it on webpage

#

?

rustic pebble
#

You can get current date with the following

from datetime import datetime
current_month = datetime.now().strftime("%m")
current_day = datetime.now().strftime("%d")
current_year = datetime.now().strftime("%Y")
rustic pebble
native tide
#

ok

#

I have postgrs and mysql installed on my laptop but I never used them

#

let me search on my own

#

gtg to eat

rustic pebble
#

You will need to use an sql module for flask

#

the one I use is Flask-SQLAlchemy

native tide
#

SQLALCHEymy

#

yes

rustic pebble
#

Which provides on ORM

native tide
#

ik that

rustic pebble
#

Object Relation Map

native tide
#

ok

#

can I ping you when i'm back?

rustic pebble
#

sure

native tide
#

thanks

#

cya

native tide
#

Will script(js) file be running on browser when rendering html using flask?

native tide
#

@rustic pebble what is that raw github link ? and from where you got that ?

#

I decide to first write a python code and then try to make a flask page on it

bright trench
#

o

past cipher
#

how to read a config key in my main route files? I thought it was something like app.config['secret_key']

#

secret key is set inside init

#

I want to read the value inside one of my routes

#

nvm done it, I imported app instead of doing from app import app

native tide
#

how does web development works with python?

pine yew
#

@past cipher you'll also need current_app inside of a view

#

@native tide the same way as other languages, through a web framework. In Python, you have quite a selection but the most stable choices are Django and Flask

#

Django gives you more tools out of the box, Flask is extensible and relies on plugins

native tide
#

why would you make a web with python instead of using basic html?

past cipher
#

thanks @pine yew I already got it sorted

#

@native tide you use Python for the back-end

#

you still need to use html

#

for front-end

pine yew
native tide
#

ohh

#

is it matter the language?

pine yew
#

no, not really

native tide
#

oh ok thanks

#

which your prefer? flask or django?

pine yew
#

I use something called FastAPI because I mostly make REST APIs at work

#

and it has a lot of great features

snow sierra
#

but, how can you explain member everything about Django to HTML ?? sometimes Youtube or other sources are better and the best than chatting here :x it is not Negative Feedback. it is reality.. as i started python, django, html, js, css and other more... i am not pro.

haughty turtle
#

when I call create_user() on a User model does this check first if the user exits?

native tide
#

@haughty turtle afaik the username has the unique constraint so if a user already exists with such a username you'll run into that error.

#

So, by that metric, yes

haughty turtle
#

Cool, thanks

#

this is correct also for email? I mean as I am not using usernames just first and last name, email, pass

native tide
#

I don't think the email has the unique constraint

#

@haughty turtle you can expand on Django's user model with your own field constraints with AbstractUser. You'll still have the User methods such as .is_authenticated etc. maybe that's what you're looking for

haughty turtle
#
def register_user(request):
    if request.method =="POST":
        request = json.loads(request.body.decode('utf-8'))
        first_name = request['fname']
        last_name = request['lname']
        email = request['email']
        password = request['password']
        re_password = request['re_password']
        if password == re_password:
            u = User.objects.get(email=email)
            if u:
                User.objects.create_user(first_name=first_name, last_name=last_name, email=email, password=password)
            else:
                pass
        else:
            pass``` @native tide Should that be good for now in checking wether email exist
native tide
#

Looks fine, but in this scenario if the email already exists, the user won't know. (User will just return an error server-side if the unique constraint isn't fulfilled). So, I would manually check whether the email is available before saving the object.

#

Oh, and that being said, you'll have to add your own constraint for email if you want it to be unique

haughty turtle
#

yeah I am going to add that in that if a email exist it will throw a setCustomValidity('Email is Already Registered.'); on the email input in my JS

native tide
#

Oh, cool. Are you using React? @haughty turtle

haughty turtle
#

Vanilla

native tide
#

Ah, ouch.

haughty turtle
#

Should I really look into using a framework?

#

I like Vanilla JS

native tide
#

Depends on your use case. If it's something simple, no bother.

#

But using a framework something like React is great, and the libraries available speeds up really tedious tasks such as forms, etc

haughty turtle
#

I will look into it after I finish the page and rewrite from Vanilla JS into a framework, my last project had 500 lines in Vanilla JS , this one probably more

native tide
#

But if you can write it in vanilla JS I think that's already gave you a boost in understanding the frameworks.

#

I went straight into React without JS knowledge and didn't know any of the terminology (I still don't understand the DOM lol) so you'll do fine

haughty turtle
#

Cool, nice to know, haha dove straight into the DOM in day 1, I mean I got the hang of JS in just one day, it was pretty straightforward.

#

Frameworks just offer a benefit in dev speed or more? guess I will have to look into it.

native tide
#

Yea, dev speed, page speed (React can manipulate the virtual DOM instead of the whole DOM, so no refreshing of the page) and makes everything AJAX and smooth.

#

I wouldn't have anything to compare it too as the only JS I use is within the framework

#

But it will differ slightly, if you use React the main language is JSX which varies but only slightly

frank wedge
#

Hello,
I need help with two question, if someone could help me.

  1. What is the proper way to chain methods based on conditions?
    If I have a class with multiple methods and on my object I would like to chain some of those methods only if certain conditions are met. How would I do that?

  2. What is the proper encoding method for transfering data to another webservice? API service.
    I'm trying to send a JSON text to another service and it seems to return an error for some characters like +, <, >... etc.
    Thank you.

native tide
#

hello everyone

devout coral
#

Hello

#

Anyone here have some experience with Boto3 and S3. I have a Django application and am wanting to migrate to using S3 for media files and maybe static as well. Would this be a simple transition assuming the application is already running and I have files locally of course? If so how would I go about doing it? Setting ip boto3 normally and it will upload everything automatically?

native tide
#

if anyone need web hosting for your websites
join this free giveaway
by my brother

lavish prismBOT
#

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

pine yew
#

!rule 6 actually

lavish prismBOT
#

6. No spamming or unapproved advertising, including requests for paid work. Open-source projects can be shared with others in #python-general and code reviews can be asked for in a help channel.

native tide
#

Oh Its a open-source-project

#

to give

#

hosting

dense slate
#

This is probably the 100000th time someone asked this but... Vue or React (or something else) and why - for Django or just in general?

pine yew
#

I like vue v3's more FP approach, just personal style

#

I also like their use of single-file components (SFC)

native tide
#
class NoteSerializer(ModelSerializer):
    class Meta:
        model = Note
        fields = ["name", "content", "notebook", "slug"]

        notebook = CharField(required=False)
        content = CharField(required=False, allow_null=True, allow_blank=True)
#

Does anyone know why even though I've specified my content field to not be required, it's still being required?

#

I guess the same guess for notebook

haughty turtle
#

@native tide Grow your email list through Viral Giveaways Not allowed and its not a open-source project, you require a email for it. It does not belong here and you might as well remove it.

#

@dense slate If you are looking for a job then React as its more popular, Vue is Opened Source, I will main it for personal projects, but employers mostly look for React based on what is being shown.

dense slate
#

Is allow_null a more recent Django change? I thought it was just null=True.

#

@haughty turtle Future employability aside, from ease of use and just pleasure of working with it, sounds like Vue?

haughty turtle
#

VueJS I have heard alot of good things about they say its the best of both worlds between React and Angular

#

Its a highly active project, and making sure to stay ahead of Google and Facebook, I will make sure to learn it as my main framework when not in relation to employment

hollow scaffold
#

Django: real quick question, is there a way to automatically create x instance of a model if x instance doesn't exist?

#

I.E. (delete all model instances,) or (new django db is created): if no instances exist, a default instance automatically gets generated

hollow scaffold
#

Thanks, I'll take a look

#

for reference this is my current fix lol, but have to pass exceptions for initial migration to not throw an error

def getMainMenu(): # TODO FIX THIS SHIT
    try:
        # Check if menu is empty
        if not MainMenuLink.objects.all():
            link1 = MainMenuLink.objects.create(title='Home', url='/')
            link1.save()

...
            logging.error(f"No MainMenuLink objects exist, creating defaults")
    except:
        pass
        # Return menu
        return MainMenuLink.objects.all()
    finally: 
        pass
#

lol

native tide
#

This is so strange

#

I'm making a new note, it's appended to my client-side "list of notes", but if I am hovering over a note when I "submit", it does not show until my mouse leaves that div (that note). I have been pondering over my code for about an hour now and im so lost...

hollow scaffold
#

@kindred whale thanks btw, works great

haughty turtle
#

@native tide Can you show a snippet of the code

#

Have you include any code that would stop the function that refreshes your items on screen from running, I have accidently done this before, where inside my function I would call an if statement to check if the item hovered is not the same to the refresh my items

native tide
#

Dude, I actually just fixed it randomly. Holy fucking shit

#

It came to the point where I'm just changing stuff randomly without thinking

#

and it worked...

#

And that "snippet" would be 500+ lines ๐Ÿ˜ณ

#

So thank god for that ๐Ÿ‘

haughty turtle
#

yeah would of loved to help back, but would of needed to review code. Glad you got it fixed though

#

you should go back step by step and undo changes until you find that ramdom piece that fixed it so you can understand the problem better for future references

#

@native tide

native tide
#

Yeah

#

It was totally unexpected because the functionality of my component essentially mirrors the functionality of ones I already wrote (successfully).

#

And going line by line, everything seemed to work fine.

haughty turtle
#

Boom created a Custom User and just registered and logged in

native tide
#

I think it's something with the inner workings of React. I have a parent component with a child component, and when I press "submit" to make that note, that child component is updating the state of the parent component.

I realized a lot of the state changes of the child component were reverting the state of the parent component to its DEFAULT. So, I just removed the state-changes from the child component, and placed it all in the useEffect hook of the parent component. And that worked.

So I think what was happening was that there was some async stuff going on not as expected, still not sure lol, don't really want to know

#

@haughty turtle Nice!

haughty turtle
#

You have any resources that would give me a depper understanding on how sessions work

#

I know there is the db, cookies, or file storage sessions

#

but I want to understand how this would be able to authenticate a user with user info being stored server side

#

Only finding detailed information on cookie based sessions

native tide
#

I'm pretty sure that Django gives every user a session token which is then stored client-side as a cookie, and on every request that token is included in the request header...

#

Actually I think I'm wrong on that one

#

Pretty sure that's token authentication which is different

haughty turtle
#

Django uses database based sessions which are stored on the database as default

#

while Flask uses cookie bases sessions as default

native tide
#

This is giving some good info so far

#

"Django uses a cookie containing a special session id to identify each browser and its associated session with the site. The actual session data is stored in the site database by default (this is more secure than storing the data in a cookie, where they are more vulnerable to malicious users). You can configure Django to store the session data in other places (cache, files, "secure" cookies), but the default location is a good and relatively secure option."

#

That's pretty confusing to me.

So, Django stores each user's session ID in a database, and stores it as a cookie. Then on every request compares the cookie ID to the session ID...

How is that different to token authentication?

haughty turtle
#

You can read it and write to request.session at any point in your view. You can edit it multiple times```
#

it seems to grab it from request.session but yeah have to dig into it

native tide
#
# Get a session value by its key (e.g. 'my_car'), raising a KeyError if the key is not present
my_car = request.session['my_car']
#

Yeah

#

The mozilla docs explain it well

#

I might need to use the session auth to track stuff like website visits

#

But I still don't get how it's different to token auth

haughty turtle
#
    if request.method =="POST":
        new_request = json.loads(request.body.decode('utf-8'))
        first_name = new_request['fname']
        last_name = new_request['lname']
        email = new_request['email']
        password = new_request['password']
        re_password = new_request['re_password']
        if password == re_password:
            try:
                u = User.objects.get(email=email)
                print('Email already in use.')
            except:
                User.objects.create_user(first_name=first_name, last_name=last_name, email=email, password=password)
                print('User Created.')
                user = authenticate(request, email=email, password=password)
                if user is not None:
                    login(request, user)
                    return redirect('http://127.0.0.1:8000/portal/')```
#

I am trying to redirect but it does nothing

late gale
#

hey can someone help me here

def delete(request, pk):
    order = OrderItem.objects.get(id=pk)
    if request.method == 'POST' :        
        order.delete
    elif order.DoesNotExist:
        order_name = order.name
        order_name.delete()

    return redirect('Cart')

    context = {'order': order}

    return render(request, 'products/delete.html', context)

i am trying to make the user delete the an order added to the cart by the id and it removed but if i came and add it again it says it does not exist because it has new id now so i am trying to delete it using order name or idk

verbal snow
haughty turtle
#

@late gale You should not be removing items from cart server side

#

That is something you take care of in the frontend, with JS

native tide
haughty turtle
#

what you are doing is deleting the item from the database so this is the reason why you are getting such error, as users should not be allowed to delete global items that other users would need, that is an admin function.

#

Will save that to read later @native tide

#

Thanks

late gale
#

@haughty turtle oh so you mean i have to use javascript to delete i will try then

#

thank you

native tide
#

@late gale you can delete by order_number and every time something is put into the cart (or bought) assign it a new unique order number

#

Just a thought.

haughty turtle
#

Could do that also, but then doing this in Django would it not be more complicated and offer worse UX, as for changes to take effect on the browser would cause for a reload, while JS does it without reloading

#

?

late gale
#

i will try both

#

and see what's better for me

#

thank you

native tide
#

Oh yeah JS would be the better option for sure

#

You'd have something like the order_number thing as an API instead in that case

late gale
#

but how i can select an order item like if i added an id to the <h1> tag this will remove all my order items not a certain one

haughty turtle
#

show me your html

late gale
#

ok

haughty turtle
#

just a snippet is fine

late gale
#
                    </div>
                    {% for item in order.orderitem_set.all %}
                    <div class="cart-row">
                        <div style="flex:2"><img class="row-image" src="{{item.product.image.url}}"></div>
                        <div style="flex:2"><p style="font-family: inherit;">{{item.product.name}}</p></div>
                        <div style="flex:1"><p style="font-family: inherit;">${{item.product.price|floatformat:2}}</p></div>
                        <div style="flex:1"><p class="quantity" style="font-family: inherit;">{{item.quantity}}</p></div>
                        <div style="flex:1"><p>${{item.get_total|floatformat:2}}</p></div>
                        <div style="flex:1">
                        <a class="btn btn-sm btn-dark" href="{% url 'Products' item.product.id %}" style="font-family: inherit;">Update</a>
                        </div>
                        <div style="flex:1">
                            <a class="btn btn-sm btn-danger" style="font-family: inherit;" href="{% url 'Products_Delete' item.product.id %}">Remove</a>

                        </div>
                    </div>
                    {% endfor %}
#

there is the part

#
                            <a class="btn btn-sm btn-danger" style="font-family: inherit;" href="{% url 'Products_Delete' item.product.id %}">Remove</a>
#

thats the remove btn

#

hope u get what i am trying to say

haughty turtle
#

you need to loop through all of your remove buttons and add a eventlistener

late gale
#

oh that might work

#

let me try

haughty turtle
#

on click then grab its parent element

#
    for ( let l = 0; l < pwLength; l++) {
        document.querySelectorAll('.cart_trash')[l].addEventListener('click', function() {
            this.parentElement.remove();
            localStorage.removeItem(this.parentElement.getAttribute('id').replace(/_/g, " "))
            let totalC = parseFloat( parseFloat(document.querySelector('#total_cost').innerHTML.replace(/[^.\d]/g, '')).toFixed(2) - parseFloat(this.parentElement.childNodes[6].innerHTML.replace(/[^.\d]/g, '')).toFixed(2) ).toFixed(2);
            document.querySelector('#total_cost').innerHTML = `Total: $${totalC}`;
            if ( cart_count () < 1 ) {
                document.querySelector('#overlay_wrapper').style.display = 'none'
            }
        });
    }```
#

this is an example that I just recently used

late gale
#

oh ok let me see

haughty turtle
#

it has some extra stuff in there but just focus on the loop, the eventlistener, and this grabs the object that your item is in get the parent and delete it.

#

check if the item count in the cart is 0 to then exit out of the cart display

#

update new total price

tacit sleet
#

Okay I'm admittedly new to Django but am a bit baffled on this one. I have django running in docker. Template loads fine. I have a file called main.js in my static folder that 404s when the template tries to load it. Works perfectly in my 'prod' docker-compose using nginx and gunicorn, but running in the dev server it 404s. What the am I missing?

#

Grabbed a shell in the container and confirmed with diffsettings that STATIC_ROOT is configured to point to that directory (/app/staticfiles), and that the file is definitely there and has the correct permissions

#

STATIC_ROOT = '/app/staticfiles'

file exists in that folder and has the correct permissions:

total 16
drwxr-xr-x 3 appuser appuser 4096 Nov 25 21:10 .
drwxrwxr-x 7 appuser appuser 4096 Nov 25 21:10 ..
drwxr-xr-x 6 appuser appuser 4096 Nov 25 20:57 admin
-rw-rw-r-- 1 appuser appuser   31 Nov 25 21:10 main.js```
late gale
#

@haughty turtle the item isnt removed yet

#

there is only one remove button i think no loop needed

#

look

#
                            <button type="submit" id="button" value="Remove" class="btn btn-sm btn-danger"></button>

                        </div>
                    </div>
                    {% endfor %}
                    <script>
                        document.getElementById("button").addEventListener('click', function(){
                            var order_item = document.getElementById("order_item").remove()
                        })
                    </script>
#

it just removed the button .

#

or wait

#

oh it worked @haughty turtle but the problem is if i refreshed it came back again

haughty turtle
#

because you have your button wrapped in a div

#

so you have to remove the parent of the parent of your button

#

@late gale have to head out

tacit sleet
#

If anyone knows django and has a moment

haughty turtle
#

also you need a loop because you have a button for every item {% for item in order.orderitem_set.all %}

late gale
#

it removed the item but it comes back on refresh

#

oh i believe u are right

haughty turtle
#

because of the for loop, on refresh it refresh everything

late gale
#

i tried to click on the second button but not worked

haughty turtle
#

so you have make sure to verify where you are grabbing your items from {% for item in order.orderitem_set.all %}

late gale
#

and how i gonna loop in this tbh

haughty turtle
#

on refresh you are setting displaying all items from django again

grizzled sand
#

Hello everyone. Could i represent this function view to class based ListView?
I've confused because in django documentation says, ListView - Each generic view needs to know what model it will be acting upon. This is provided using the model attribute.
as i understand with model = My_model, but if i want add more the one model to this view, how can i do that?

Thanks!

def index(request):
    '''
    Function for display homepage
    '''
    # Generate count main objects
    num_books = Book.objects.filter(genre__name__icontains='').count()
    num_instances = BookInstance.objects.all().count()
    num_genres = Genre.objects.all().count()
    # Avalible books (status='a')
    num_instances_avalible = BookInstance.objects.filter(status__exact='a').count()
    num_authors = Author.objects.count() 
    num_articles = Article.objects.filter(category__name__icontains='').count()

    # Number of visits to this view, as counted in the session variable.
    num_visits = request.session.get('num_visits', 0)
    request.session['num_visits'] = num_visits+1

    # Render HTML-tamplate index.html with data inside variables 'context'
    return render(
        request,
        'index.html',
        context={
            'num_books': num_books, 
            'num_instances': num_instances, 
            'num_instances_avalible': num_instances_avalible,
            'num_authors': num_authors,
            'num_genres': num_genres,
            'num_visits': num_visits,
            'num_articles': num_articles,
        }, 
    )
haughty turtle
#

I have to head out wife is waiting for me, instead of using django to display each item in your cart try to use js

late gale
#

but i want it to be deleted forall

#

ooh np take care

haughty turtle
#

So when a user clicks add to cart you send the items they added over to Django? @late gale

late gale
#

yes

#

thats why i need to use django to delete

haughty turtle
#

@late gale are you dealing with registered users?

snow sierra
wary turret
#

Hello! I'm looking to start a personal project that needs a webserver backend. Just a few endpoints and some light DB access. Is Flask still the way to go? or is there something new/interesting I should check out?

haughty turtle
#

@snow sierra because I sent a POST through fetch in JS,

#

My items was attached into it's body as JSON

snow sierra
#

oops sorry, yes ( request = json.loads(request.body.decode('utf-8')) )

late gale
#

@haughty turtle nope guest users

haughty turtle
#

If you are using guest user then no reason to send this over to Django

late gale
#

i did i can remove all the orders using django from the remove button but cant remove specific one

haughty turtle
#

Could be due to the cascade on delete, show your model, but what I want to say is that if you are logging a user in then you shouldn't be sending this over to Django until the user is ready to finalize the purchase then you cross reference your items from your models to make sure they are paying the correct price.

trim star
#

I am trying to run unit tests in django python3 manage.py tests and I get the following error:

django.contrib.messages.api.MessageFailure: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware
#

And messages is in INSTALLED_APPS

#

and MIDDLEWARE

haughty turtle
#

Even then if you log a user, me personally I would save this as a JSON through the use of fetch and save it under my User model. Then I would be able to grab it and loop through it. Even then point being you will still need JS to provide better UX, the way you are going would require a reload. @late gale

#

The way you are displaying your items in your HTML requires a reload for changes to take effect. Not recommended

vestal hound
#

@grizzled sand that doesnโ€™t really work... it has to be one model per view.

#

can be nested thoughthis

gaunt marlin
#

i presume that you also had django.contrib.messages in your INSTALLED_APPS

twilit needle
#
import axios from 'axios';
import pixStore from '../redux/store';

axios.defaults.xsrfHeaderName = "X-CSRFToken"
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.headers.common['Authorization'] = JSON.parse(pixStore.getState().token);

export default axios;```
#

I did this to make axios default headers but still my requests are failing because they arent authorized

#

the api says I need the auth token in the header

#

But I already have it, right?

#

What am I doing wrong here? pls help me

#

I console.logged JSON.parse(pixStore.getState().token) Its the correct token

gaunt marlin
#

most api will also following the format of "Authorization: Bearer <token>"

twilit needle
#
xhr.js:177 POST http://127.0.0.1:8000/api/logout/ 401 (Unauthorized)
(anonymous) @ xhr.js:177
e.exports @ xhr.js:13
e.exports @ dispatchRequest.js:50
Promise.then (async)
l.request @ Axios.js:61
r.forEach.l.<computed> @ Axios.js:87
(anonymous) @ bind.js:9
onClick @ sideBar.jsx:41
We @ react-dom.production.min.js:52
Ye @ react-dom.production.min.js:52
(anonymous) @ react-dom.production.min.js:53
Er @ react-dom.production.min.js:100
Cr @ react-dom.production.min.js:101
(anonymous) @ react-dom.production.min.js:113
ze @ react-dom.production.min.js:292
(anonymous) @ react-dom.production.min.js:50
Nr @ react-dom.production.min.js:105
Zt @ react-dom.production.min.js:75
Jt @ react-dom.production.min.js:74
t.unstable_runWithPriority @ scheduler.production.min.js:18
$o @ react-dom.production.min.js:122
Le @ react-dom.production.min.js:292
Gt @ react-dom.production.min.js:73
sideBar.jsx:46 Error: Request failed with status code 401
    at e.exports (createError.js:16)
    at e.exports (settle.js:17)
    at XMLHttpRequest.p.onreadystatechange (xhr.js:62)```
#

ohh

#
axios.defaults.headers.common['Authorization'] = 'Bearer ' + JSON.parse(pixStore.getState().token);
#

like this?

#

@gaunt marlin

gaunt marlin
#

yeah

twilit needle
#

or the <>

#

is required?

gaunt marlin
#

no need for <>

twilit needle
#

okayb thanks Ill try it

gaunt marlin
#

i just use it to tell it's for token

twilit needle
#

okay

#

still same error..

#

idk why

#

does 401 indicate something else

gaunt marlin
twilit needle
#
function logoutUser() {
        axios.post('/api/logout/')
            .then(() => {
                dispatch({type: "CLEAR_AUTH"});
                <Redirect to='/login/' />
            })
            .catch(error => {console.log(error)});

    }```
karmic egret
#

can anyone suggest me some helpful tutorial for flask-security

twilit needle
#

this is how I make the request

#

and I import axios from here

import axios from '../../tools/csrfConfig';``` where I defined the default headers
#

anything wrong here?

gaunt marlin
#

which system are you using for authentication?

#

firebase? jwt?

twilit needle
#

token auth django

twilit needle
#

my other endpoints which dont need authentication are fine

gaunt marlin
#

i think you mean authToken of DRF, not Django(django don't have it)

#

jwt you use Bearer, auth token you use Token

twilit needle
#

yeah the rest framework thing

#

i meant

glass badger
#

Can Django work as a sub-domain to a SquareSpace website?

twilit needle
#
axios.defaults.headers.common['Authorization'] = 'Authorization: Token ' + JSON.parse(pixStore.getState().token);``` am trying this @gaunt marlin
gaunt marlin
#

@twilit needle don't do that, you don't need the after authorization

twilit needle
#

okay

#

lol

#
axios.defaults.headers.common['Authorization'] = 'Authorization ' + JSON.parse(pixStore.getState().token);```
#

this?

#

it doesnt work though

#

same error in console

gaunt marlin
#
axios.defaults.headers.common['Authorization'] = 'Token ' + JSON.parse(pixStore.getState().token);

is ok , i don't know about axios so i guess this is the way to set header

twilit needle
#
http http://127.0.0.1:8000/hello/ 'Authorization: Token 9054f7aa9305e012b3c2300408c3dfdf390fcddf'```
#

I saw this example

gaunt marlin
#

yeah

#

did it worked though?

#

the api supposed to return status code of 200

twilit needle
#

yeah but it didnt

#

one sec

#
@api_view(["POST"])
@permission_classes((IsAuthenticated,))
def logout(request):
    try:
        request.user.auth_token.delete()
    except (AttributeError, Exception):
        pass
    logout(request._request)
    return Response(status=HTTP_200_OK)
#

this is my view

gaunt marlin
#

what did the api return?

twilit needle
#

401

#

not authorized

gaunt marlin
#

did you check your token? to see if it's correct?

twilit needle
#

um yes

#

its correct

#

am sure

#

am referring to this

#

GUESS WHAT IT WORKED

#

and I know why

#
axios.defaults.headers.common['Authorization'] = 'Token ' + JSON.parse(pixStore.getState().token);
#

we're supposed to do this

#

the Authorization: part was this

#
axios.defaults.headers.common['Authorization']
#

axios automatically passes it as a dict

#

so we shouldnt do Authorization:

gaunt marlin
#

well yeah that what headers.common is for

twilit needle
#

yeahh

gaunt marlin
#

set the header values

twilit needle
#

lol I was so stupid

gaunt marlin
#

so it can pack into dictionary

gaunt marlin
twilit needle
#

Ohh

#

sorry I think I mistook you

#
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
#

now I get this error duh

#

when I try to login

#
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import {useSelector} from 'react-redux';
import {IsNull} from '../../tools/easierJavascript';

const PrivateRoute = ({component: Component, ...rest}) => {
    const user = JSON.parse(useSelector(state => state.user));
    return (
        <Route {...rest} render={props => (
            (!IsNull(user)) ? <Component {...props} /> : <Redirect to='/login/' />
        )} />
    );
};```
#

problem is with this

gaunt marlin
#

well that is axios error which i'm no expert in

twilit needle
#

no its reactjs error

#
function AppRouter () {
    return (
       <Router>
           <div className="appRouter">
                <Switch>
                  <PrivateRoute path='/app/' component={App} exact />} />
                  <Route exact path="/" render={() => (<Redirect to="/app/" />)} />
                  <AuthenticationRoute path='/login/' component={LoginMount} />
                  <AuthenticationRoute path='/register/' component={RegistrationMount} />
                </Switch>
            </div>
       </Router>
   );
#

So I have a router for my app

gaunt marlin
#

well react use axios to doing requests

twilit needle
#

and it has PrivateRoute components

gaunt marlin
#

oh ok got it

twilit needle
#

the private route component is running an infinite loop?

#
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.```
#

I got this error

#

nevermind

#

I think I solved it

#

I didnt json.parse the user in another component

gaunt marlin
iron beacon
#

gn everyone

I'm kinda new to web-dev, mostly the authentication part got me confused

My question is how is token more secure then username and password authentication to REST APIs?

I'm currently developing a REST API and there's a endpoint to retrieve the user token based on its username and password.

In that case is not the same thing? If someone get your password it might aswell get your token in that way

gaunt marlin
#

@iron beacon token is to identify which user calling the api,
you first send username/password to authenticate that user is correct and give them a short live token, for example to call /profile api you would send user token instead of sending username/password again. If you want to secure from man in the middle attack(if someone stole your token), this is where SSL come in, it's use to encrypt your network traffic. If you use authentication setting up SSL is MANDATORY. TLDR: Token itself don't have any security, it just use to identify user, if you want secure then encrypt your api host with SSL

iron beacon
#

Oh, so that's why the DRF documentation mentions that you need to use HTTPS instead of HTTP when working with tokens

gaunt marlin
#

yep

hushed barn
#

@ me if you have an answer pwease Thanks!

vestal hound
hushed barn
vestal hound
hushed barn
vestal hound
#

there is a time and place to act cute, but this isn't it IMO...

#

so is it actually running?

#

check your terminal

hushed barn
vestal hound
hushed barn
# vestal hound `python manage.py runserver`...?

That feeling when your so dumb how did i not remember every time i restart i gotta run the server Thank you! maybe i should quit coding when i still can i probably should not code when im 10

native tide
#

hii

native tide
#

hiya

native tide
#

Hi

#

I want to compare modell value with request value ( Django )

#

log

{'type': 'textbox', 'group': 'content', 'name': 'textbox_00', 'settings': {'text': 'Ny text?'}}
{'type': 'inputs', 'group': 'content', 'name': 'inputs_01', 'settings': {'input1': 'Ja', 'input2': 'Nej', 'type': 'button'}}
<QuerySet [<SettingsPair: input1: Ja>, <SettingsPair: input2: Nej>, <SettingsPair: type: button>]>
None
{'type': 'textbox', 'group': 'content', 'name': 'textbox_00', 'settings': {'text': 'Ny text?'}}
{'type': 'inputs', 'group': 'content', 'name': 'inputs_01', 'settings': {'input1': 'Ja', 'input2': 'Nej', 'type': 'button'}}
#

code

for ui in found_question_uis:
        settings = print(ui.settings.all())
        print(settings)
        for req_ui in request_ui_components:
            print (req_ui)
haughty turtle
#

@hushed barn everyone hits the point you have hit and makes silly mistakes wether you are 10 or 50 or anywhere in-between learning something new is the same for everyone. I started around that age messing with C++ and regret giving up to just pick back up on it at 23 years old. Also you should probably stop stating that you are under the age of Discord ToS might get your account suspended, either way your never to young or old to learn how to code.

meager pecan
#

do run python print("HELLO")

#

no bot?

haughty turtle
#

๐Ÿค”

weary dragon
#

Hello guys, have you some resources from where i can learn django? i have some experience with flask

native tide
#

@weary dragon pretty printed / corey shafer do great django courses

weary dragon
#

alright then, thanks

native tide
vestal dove
feral condor
#

hello I have this model in django ```class Trip(models.Model):
bus = models.ForeignKey(Bus, on_delete=models.PROTECT, related_name='trip_detail')

class Seat(models.Model):
bus = models.ForeignKey(Bus, on_delete=models.PROTECT, related_name='seats')
label = models.CharField(max_length=100)
x = models.PositiveIntegerField()
y = models.PositiveIntegerField()

class Bus(models.Model):
number_plate = models.CharField(max_length=100, primary_key=True)
travel_agency = models.CharField(max_length=256)```how can i serialize Seat fields from Trip?

#

travel_agency = serializers.ReadOnlyField(source='bus.travel_agency')gives travel_agency but couldnt reach Seat fields

sterile peak
#

I am going mad trying to work with zeep and one WSDL.. is there anyone experienced with this

native tide
#

@vestal dove you need to use blueprints

#

@feral condor Open the database in a DB viewer (SQLite browser) and see what fields were generated

#

Then you will know how to navigate

versed python
#

Anyone here who has worked with Django and ariadne? I am having a tough time implementing user authentication and want to see some example repos if you have one.

native tide
#

Hey guys... I am looking to build an application that is going to have two bits that need to work independently. One would be talking (mostly receiving) to a MQTT bus, the other one would offer a REST API to serve as an endpoint for a system downrange. I did something similar a couple years ago and then I decided to use Threading. I ran my server in one thread and web server in the other while they exchanged data throuh Queues.

I guess my question would be what would be the go-to approach for something like this today?

Thank you in advance for any advice you may give!

haughty turtle
#

Could you not also use a text file called logs and check up on it to then see when its updated and if so then read it and perform a action, as far as best practices I do not know, I have done something similar with Sockets for apps on different system, but if they are on the same seems like a log file would serve the purpose

#

Ah take a look at this

#

@native tide

native tide
#

@haughty turtle yes, I have considered this option too.

haughty turtle
#

@native tide

thin dome
#

anyone here?

#

i want help

#

with my django project

#

i am facing a error

#

error is '<module 'home.urls' from 'D:\\Programs\\Hello\\home\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

verbal snow
thin dome
#

are u reponding to me?

verbal snow
#

How would I respond to you with and admin panel error?

thin dome
#

sorry

native tide
#

@thin dome show us urls.py

thin dome
#

can u help me?

#

ok my app one or project one? @native tide

native tide
#

home\urls.py

thin dome
#

ok

#
from django.urls import path
from home import views

urlpatterns = [
    path("", views.index, name="home")
]
native tide
#

@verbal snow 'User' object has no attribute 'pk' What is your User object in this case?

#

@thin dome did you register you app in settings.py

thin dome
#

how to? in tutorial he doent open settings.py @native tide

#

i m learning so idk that error and other stuff

native tide
thin dome
#

i only now how to register templates

#

ok

verbal snow
trim star
thin dome
#
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]``` @native tide
native tide
#

what is your appname? is it home? If so, add 'home` to installed_apps

thin dome
#

yes

#

how?

#

django.contrib.home?

native tide
#

@verbal snow Do you know what file that error is in, User object has no attribute pk?

#

@thin dome No, just 'home'

thin dome
#

ok

native tide
#

The name of the app

thin dome
#
    'home'
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]```
#

like this?

native tide
#

well, no, it's a list

#

you missed something out

thin dome
#

then how?

native tide
#

the clue is

#

it's a list

thin dome
#

im starting django please help me

#

pleaseeeeeee

verbal snow
#

Looks like admin logs

native tide
#

@thin dome Yeah, that's not a django problem, that's a basic python problem. Give me an example of a list.

thin dome
#

a = [1,1,2,2]

#

thats a list

native tide
#

Now compare that to your INSTALLED_APPS

thin dome
#

['home']?

native tide
#

@verbal snow I'm gonna need more information than the error, maybe you're calling .pk incorrectly? I don't know

verbal snow
#

I'm not calling it

#

This is a django file calling it

native tide
#

Ok, do you have a custom User model?

thin dome
#

is it ['home']?

verbal snow
#

No

thin dome
#

help mememememememememeeeeeee

native tide
#

@verbal snow So what are your models looking like?

#

Flask or Django. Which is best?

#

And WHy?

thin dome
#

flask for small apps django for big

native tide
#

@thin dome You just gave me an example of the list. Now compare it to INSTALLED_APPS.

native tide
thin dome
#

please nobody torched me this much

#

yes

native tide
#

I'm asking this question so you will learn

#

Instead of just giving the answer

thin dome
#

i am learning it too @native tide

native tide
#

you need a comma after 'home'

thin dome
#

ok nice mentor

native tide
#

so I asked you to compare it to your list so that you'd see that you need a comma

thin dome
#

is this right?

#
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',```
native tide
#

what type is INSTALLED_APPS

#

Can we do the things which JS can do like adding animations to button with django?

#

@native tide Not really, unless you use CSS animations

#

Django is a backend framework

thin dome
#

INSTALLED APPS is list

native tide
#

exactly... so why are you doing this? ['home']

#

Ohk and can we render js(frontend js) with django.

#

yep

#

within a html?

#

mhm

#

like having a js file for html.

#

and we render html so that js is also rendered.

thin dome
#
    'home',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]```
native tide
#

You mean <script> within html? Yea

#

@thin dome that's right

native tide
thin dome
#

but i am getting this error again

native tide
#

Then its fine i can then make a nice frontend too.

untold topaz
#

Anyone here familiar with XML and XML Queries??

native tide
#

@thin dome then you need to sort out the urls.py in your root directory

verbal snow
native tide
#

Do you have any project with django like having a text box linked with sql?

verbal snow
#

this is my models

#

but the error looks like it has to do with the admin User model

#

I have my own user model

thin dome
#

this is my rootROOT_URLCONF = 'Hello.urls'

verbal snow
#

But it is not sub classing the admin one

native tide
#

@verbal snow Possibly, in your admin model are you setting this?:

unique_id = models.AutoField(primary_key=True)```
native tide
#

@thin dome No, open up the urls.py , you should have 2

#

Want to see how the code looks like.

thin dome
#

yes

native tide
thin dome
#

this is my hello url=```from django.contrib import admin
from django.urls import path,include

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('home.urls'))
]

#

no i was saying it to @native tide

native tide
#

Ohk

thin dome
#

u indian?

native tide
#

Yes.

simple surge
#

hi

simple surge
#

I`m, luqm,an

verbal snow
#

I'm not editing any admin models, nor am I subclassing any of them

thin dome
#

@native tide

native tide
#

@verbal snow But you made your own admin model, right?

native tide
thin dome
#

no my many frnds name is vishal

#

in india

native tide
#

Ahh i see.

#

Hmm Vishal is an Indian name.

thin dome
#

yes

verbal snow
#

Thats what I've been trying to say

thin dome
#

man help meeeeeeeeeeeeee

verbal snow
#

I'm not doing anything with any admin models

thin dome
#

@verbal snow can u help me?

verbal snow
#

What is it?

thin dome
#

mproperlyConfigured: The included URLconf '<module 'home.urls' from 'D:\Programs\Hello\home\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

#

this error

thin dome
#

i have gone to that website

#

i cant understand anything

native tide
#

@thin dome give your urls names

#

name="url_name"

thin dome
#

can u come to vc i will screen share

native tide
#

no

thin dome
#

ok

#

is this what u want

#
from django.urls import path
from home import views

urlpatterns = [
    path("", views.index, name="home")
]
#

this is my app urls

native tide
#

give it a path, like 'example/' and see what the issue is then

thin dome
#

i was creating fornt page

#

means if there is just url then it will go home page

#

so its just " "

native tide
#

Ok, it was just a debugging thing, what's your views.index?

thin dome
#

# Create your views here.
def index(request):
    return HttpResponse("this is homepage")```
native tide
#

So if you want it in the homepage, why don't you just do
path("", views.index(whatever the route is), name="homepage") in your main urls.py

thin dome
#

:[ i cant understand

#

i am just following tutorial

verbal snow
#

whats so hard to understand

thin dome
#

@native tide

#

@native tide your are bestttttttt guy i ever met in django field

native tide
#

so is your issue fixed now?

thin dome
#

yes

#

but include doent work

#

but i think thats ok

#

this is my main urls```from django.contrib import admin
from django.urls import path,include
from home import views

urlpatterns = [
path('admin/', admin.site.urls),
path("", views.index, name="homepage"),
]

native tide
#

because in your main urls.py, you are specifying the routes for your apps.

so

path("products/", include(products.urls))```
will setup a url for `site/products`

Then in your `products` app you can do:

```py
path("product-1/", views.index, name="product-1")

which is for the url site/products/product-1/

So if you have an app, make sure it has it's own url.

thin dome
#

ok can i dm u if i face error?

#

or no?

native tide
#

use google

thin dome
#

ok

native tide
#

Can we do register and login logic from a single route in django?

#

@native tide yep

#

@native tide give me some hints

#

how would you do that?

#

I want home address to be redirected to login/register page

#

can't you just have 2 forms which do different things when submitted

#

when they are not logged in or registered

native tide
#

Can I redirect to two different pages? (login and home) from a single (home address) route?

#

@native tide

#

why not

#

sure

#

again, I need hint for that

#

that would be awesome

#

anyway, are you working on ML project sir?

#

well, if Login form is submitted, redirect to x, if signup form is submitted, redirect to y

#

not atm but I'd be interested to hear about it

#

but, the project urls.py file would give me an error if I set two app with same route ('') right?

haughty turtle
#

In your view @native tide

#

In your urls.py it would grab the first one that matches

native tide
#

@native tide Oh I misunderstood that question

#

say, I have an app for home route leading to dashboard with an empty route in projects, urls.py

#

You can have one route, have a view, that view can take information from the request (which specifies stuff, like login or register and THEN redirect you to another route)

#

and same for login page (app)

haughty turtle
#

The norm is that you send a user to login and from there you place a link that sends them to the register page

#

@native tide

native tide
#

Well can you explain in layman terms what you want to achieve?

haughty turtle
#

He just wants to create a normal login registration page, but the thing is @native tide that you would have no way to find out if the user wants to login or register without them clicking a link for either or

native tide
#

then, I also don't want the login/register page routes to be url/login or url/register

#

got me?

haughty turtle
#

Well how would you know what a user wants to do ?

native tide
#

wdym?

haughty turtle
#

You have to have a link saying to either register or login, from there you can use JS to display the either form depending on which was clicked

#

You want the log in and register to be on the same page correct, you can choose to display a log in form and have a Register Account link under the form

#

Upon clicking the link with JS you can hide the display of the login form and show the sign up one

#

You send a fetch POST to the server and specify wether it's a Login or Signup and handle that in your views.

native tide
#

Still don't know what he wants lol. You can have the login/register on the same page, and if LoginForm.is_valid() you can redirect to (/homepage/) and you can do the same for the RegisterForm, it's got nothing to do with the routes

#

Can I DM one of you guys to show what I am trying to make?

haughty turtle
#

And you are struggling to toggle which forms to display?

native tide
#

nop

#

I am struggling to think how will I apply that in django

haughty turtle
#

in Django all you need is a view to send a POST request through fecth in JS that contains your form data and then type of form sent wether Login or Register.. with that you either register the user and log them in or just log them in and then send them to the dashboard

native tide
#

I feel like I am getting it finally

#

prolly makes sense when I implicate that

tacit sleet
#

Yesterday someone that was helping me with a Django issue mentioned that they hadn't done Django in a while - is that because Django isn't the best option for a python frontend and I should consider something else? I'm building a portal a user will oauth into to manage some settings (via API calls to another service) and take a subscription payment via Stripe

native tide
#

are you good at JS?

tacit sleet
#

Writing JS for this is my first real exposure to it, so no

native tide
#

php?

tacit sleet
#

I'd prefer not - I'm familiar enough to know I'm not a huge fan of PHP

#

if I did something other than python it'd be JS, but that's a bigger undertaking since I'd have so much to learn

#

If the answer is python is a bad option and just go learn JS I'm okay with that

native tide
#

I am no expert but Python isn't bad. But, if you were familiar with JS, I would suggest JS. But, if you have to start from the beginning, it doesn't worth

#

because django is capable of doing your things

tacit sleet
#

thanks!

haughty turtle
#

Django for backend, JS frontend

#

JS is built into the browser client side so it allows for real time changes in the browser while you secure your website and any sensitive info with Django and it's backend which handles any request sent to your server

tacit sleet
#

yeah that's what I'm doing now. Using JS to do the event handling for button clicks and passing things to django for payment/etc.

native tide
#

in django how to add like a global filter to a model. So everytime this model is called, that filter is applied to it before.

tacit sleet
#

I just wanted to make sure I shouldn't go to an all JS solution like node or something

haughty turtle
#

Seems like Django offers better security and faster deployment then node.js

quick cargo
#

thats low key comparing an entire language to a framework tho

surreal nest
#

Hi guys

#

I have a question about the http protocole

#

Letโ€™s say a client made a request and the server responded back

#

How does the client know how to ask new requests depending of the serversโ€™s answer ?

haughty turtle
#

How are you sending out the request ?

#

@surreal nest

surreal nest
#

with a tcp connection

#

With the socket module

surreal nest
#

Nvm, seems that the client make himself the new request depending on the response of the server

native tide
#

@native tide what's your ML project btw?

minor horizon
#

I just have created a fast api running in a docker container. It shows that it's running, but it's absolutely not responding to my posts. Any ideas?

#

This is the dockerfile:

FROM python:3.6.9-alpine

WORKDIR /fapi

COPY . /fapi

RUN pip install --upgrade pip setuptools wheel
RUN pip install -r /fapi/requirements.txt

EXPOSE 8000

CMD [ "uvicorn", "api:app" ]

And I run it via: docker run -p 8000:8000 fapi:test

And this is the output:

INFO:     Started server process [1]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
native monolith
#

curl - X POST localhost:8000/

minor horizon
#

Yea I have tried that:

#

And no logs/stdout in docker logs

native monolith
#

is your app working on this port ?

minor horizon
#

Yep,

native monolith
#

๐Ÿค”

#

maybe container has different addres

#

localhost is inside I think

minor horizon
#

Sorry, what do you mean by address?

native monolith
#

127.0.0.1 aka local host is reachable as localhost inside, but im not sure

minor horizon
#

I would love to if you help me, I'm kinda stuck here

#

Hmm

#

I just tried 0.0.0.0, not working either

#

when I run it via like uvicorn api:app, it works well. Without docker

#

PORTS seems right, right?

#

curl -X GET 0.0.0.0:8000/ i get the error curl: (56) Recv failure: Connection reset by peer

native monolith
minor horizon
#

This worker, thanks! But I doesn't fit for me yet, I need to understand this

#

What if I don't want to use host's network, isn't the isolating containers best practice?

native monolith
#

I would tell you If I knew

minor horizon
#

I see. Thanks a lot!

native tide
#

Has anybody deployed a django + react application before? What hosting service did you use? Please let me know ๐Ÿ™‚

haughty turtle
#

Would it be any different than a normal setup?

native tide
#

I don't know what the "normal" setup is

haughty turtle
#

check out linode

native tide
#

I feel like linode doesn't have the relevant reputation to be able to discuss on a resume...

#

Compared to something like AWS or GCP

#

but I've heard AWS is not for beginners

#

so I think I'll use heroku or GCP

#

or digital ocean. but i've not heard much about that

haughty turtle
#

Umm what's the difference between Linode and AWS?

#

Aren't they both VPS

#

@native tide

short nacelle
#

AWS is awesome, use S3 Buckets to host static websites

thin dome
#

how to use render?

gaunt marlin
#

render of Django?

thin dome
#

yes

#

how to use it

humble rapids
#

I know this is unrelated. But does anyone here have a good understanding of the library 'pyglet' in python and would be willing to help me out?

native tide
gaunt marlin
#

@thin dome render() is to use within your app views, it render which html template to return with values passing to that template. To read more on the function you can see this https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render
If you haven't done the django tutorial pages it mention on how to use it https://docs.djangoproject.com/en/3.1/intro/tutorial03/#write-views-that-actually-do-something

thin dome
#

ya i solved it

pseudo marsh
#

Hey there, I needed some help with html

on this page
https://leetcode.com/problems/poor-pigs/

Inspect element, and you will find a div tag like this:
<div class = "content__u3I1 question-content__JfgR" >

I'm not so good with web development, Could someone help me figure out where this class = "content__u3I1 question-content__JfgR"is?
I want to copy the question description from the page and format it just like it is formatted on leetcode

I tried looking at the link rel stylesheets thing in the <head> tag but I couldn't figure it out

vestal hound
karmic egret
#

can anyone suggest me helpful videos and article for flask security, especially on how can I manage and personifize my own login, logout, etc websites

pseudo marsh
vestal hound
pseudo marsh
#

and how'd you tell it was automatically generated

#

oh it isn't?

vestal hound
#

I would imagine the CSS and HTML protected by copyright

#

shrug is my guess

pseudo marsh
#

that sounds really weird

vestal hound
#

anyway

pseudo marsh
#

lol that was the only reason?

vestal hound
#

or just the question?

pseudo marsh
#

No just the question

#

Also I'll brb in a few mins

rustic pebble
#

Frontend framework for sure, React does that

pseudo marsh
#

will not be able to respond till thhen

pseudo marsh
#

aight I'm back

pseudo marsh
pseudo marsh
rustic pebble
#

Yes

#

Learn react

pseudo marsh
#

very insightful

#

thanks for the time anyway.

rustic pebble
#

Well React is a huge frontend framework, there is nothing easy going with it lmao

#

@pseudo marsh

pseudo marsh
#

I mean

#

I didn't intend to have it identical, just something that looked similarly formatted to that piece of text
I don't think that would require me to invest time into react imo

vestal hound
#

define "similarly formatted"

pseudo marsh
#

For now I'll just do with the bareblocks html part of it and add some backticks in there to make a few words stand out and that'll suffice

#

Have a similar look

rustic pebble
#

You cannot replicate SPA-like behavior without a SPA framework and as all things, learning one takes time and devotion

vestal hound
pseudo marsh
#

yeah I didn't anticipate a task as simple as this would require all that effort, is all

vestal hound
#

I have no idea what you mean by the "look"

rustic pebble
#

Do you mean by how the classnames appear?

#

Or by the styling of the web page?

vestal hound
#

which is a pretty subjective thing

rustic pebble
#

ye

vestal hound
pseudo marsh
#

what I mean is

#

I have this

#

on my screen

rustic pebble
#

Yes

pseudo marsh
#

I just wanted to have this piece of text somewhere else

#

and for it to have the same look as this

rustic pebble
#

That's styling and has nothing to do with react

vestal hound
#

basic CSS

rustic pebble
#

or frameworks

#

yup

vestal hound
#

do you know CSS?

pseudo marsh
#

Right, and I figured the styling depended on the class name which was kinda what I think I asked originally

vestal hound
#

do you know how CSS classes work?

pseudo marsh
#

Yeah a bit, and I figured the style for this was coming from the css class I asked about earlier?

rustic pebble
#

There is no css class actually, you create an element, you create a class attribute for that HTML element then you can directly edit that element's style by using its class name as an identifier in css

#

So basically

pseudo marsh
#

ie, I wanted the definition for the class so I coudl have a similar wstyle

rustic pebble
#
<p class="test">this is a test paragraph</p>
#

This has a class with the name of test

#

in order to style that object you can do 2 things

#

either in-line styling by adding a style attribute

vestal hound
#

in this specific case

#

those classes are for content projection

#

not for styling the question text itself

rustic pebble
#

or by creating a css file and doing the following

.test {
  /* add style here
}
pseudo marsh
#

I understand that, which was why
<div class = "content__u3I1 question-content__JfgR" >
I was looking for where "content__u3I1 question-content__JfgR" was defined

#

oh

rustic pebble
#

that's for content projections yet

#

it probably inherits style from a parent element

pseudo marsh
#

right

vestal hound
#

just HTML

#

and a cursory examination of the HTML appears to bear that out

pseudo marsh
#

oh right

#

wait what's the difference between

#

content projections and well, the style for the question being displayed?

vestal hound
#

dynamically creating content.

#

for example

#

workflow might be like

#
  1. fetch question data from DB
  2. parse question data
  3. render question data into its slot <- this is content projection
#

styling affects the process of rendering i.e. what it looks like

#

as opposed to what it is

pseudo marsh
#

content projection is just the 3rd point in that list, is that what you meant by the arrow?

vestal hound
#

so the classes you originally talked about can be thought of as internal bookkeeping data so the framework "remembers" where the content should be

#

on the other hand, styles are about, given certain content, what it should look like

vestal hound
#

and

#

that's basically a bunch of strong, code, ol etc. tags.

pseudo marsh
#

oh so like, content projections is for structuring the page
styling is for actually formatting individual parts of the structure, did I understand that right?

vestal hound
#

something like that

#

content projection is a HTML thing

pseudo marsh
#

and styling is a css thing, yeah?

#

well I guess that makes sense

#

Thank you both of you ๐Ÿ‘

vestal hound
#

yw

vestal hound
#

the CSS is not really relevant

#

it's just HTML tags

#

look at the HTML generated and you can tell

pseudo marsh
#

oh right

#

so I was able to copy just the html part of it and I got this

#

Which looks just the same

#

right, this was so simple and I'd been struggling for so long

#

thank you ๐Ÿ™‚

vestal hound
#

yw! ๐Ÿ‘‹

native monolith
#

what is general method for returning results to user from backend ?

#

new route? access to resource? other?

vestal hound
#

or use WebSockets

#

or SSEs

#

you mean like

#

delayed right

native monolith
#

yes, return image after x time

#

id? so what you mean by id?

vestal hound
#

that lets the client do a separate GET request

#

then the client polls periodically

native monolith
#

so I redirect him to template and pass ID ?

#

or js and same page

vestal hound
#

up to you

native monolith
#

thats why I asked for general case ๐Ÿ˜„

vestal hound
#

there is no general case here

#

that said, for polling you would at least need some JS in either case

#

even if you're not running a SPA

native monolith
#

yes yes thanks ๐Ÿ˜„

#

I also wonder how to make upload progress bar ๐Ÿค” , since I am runnig local I do no see when upload happens

#

is it when I click submit or when it is sending post request?

native monolith
#

i rephrase question

vestal hound
#

or do you mean like

#

on the backend?

#

sorry I don't really understand

native monolith
#

File upload happens at POST request or GET in FORM input?

vestal hound
#

POST

native monolith
vestal hound
#

wait

#

why would there be a GET

native monolith
#

page without post ๐Ÿ˜„

#

I run js here and do basic validation then redirect to page with only POST

vestal hound
#

but your form submission is still a POST, right

native monolith
#

yes, I get files with POST

vestal hound
native monolith
#

yes

#

Form is on GET page, and redirects to POST

  <form action='{{ url_for("validate_image") }}'
        method="POST" enctype="multipart/form-data"
        onchange="ValidateFileIfImage()"  >
    ...
    <button id="submitBt" type="submit" class="btn btn-primary">Confirm</button>
grizzled sand
#

@vestal hound Hm it works.
You just need define get_context_data in your view.

        context = super(IndexListView, self).get_context_data(**kwargs)
        context['team_list'] = Team.published.all()
        context['servicesPackages_list'] = ServicesPackage.published.all()
        return context ```
past cipher
#

trying to deploy via Heroku, and i'm getting internal server error

#
2020-11-27T11:07:45.292994+00:00 app[web.1]: Traceback (most recent call last):
2020-11-27T11:07:45.292995+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 134, in handle
2020-11-27T11:07:45.292995+00:00 app[web.1]: self.handle_request(listener, req, client, addr)
#
2020-11-27T11:07:45.292996+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 175, in handle_request
2020-11-27T11:07:45.292996+00:00 app[web.1]: respiter = self.wsgi(environ, resp.start_response)
2020-11-27T11:07:45.293088+00:00 app[web.1]: TypeError: module.__init__() argument 1 must be str, not dict
#
020-11-27T11:07:45.416214+00:00 app[web.1]: respiter = self.wsgi(environ, resp.start_response)
2020-11-27T11:07:45.416214+00:00 app[web.1]: TypeError: module.__init__() argument 1 must be str, not dict
2020-11-27T11:07:45.416474+00:00 app[web.1]: 10.61.214.174 - - [27/Nov/2020:11:07:45 +0000] "GET /favicon.ico HTTP/1.1" 500 0 "-" "-"
2020-11-27T11:07:45.417231+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=thawing-dawn-32152.herokuapp.com request_id=81d3082f-9625-4693-a85c-3d1c300dfe06 fwd="82.44.25.251" dyno=web.1 connect=1ms service=3ms status=500 bytes=244 protocol=https
#

any idea what is wrong ?

leaden perch
#

Hi everyone who know flask?

native monolith
#

do I need to expose port in docker?
when im using ports in dockercompose? ๐Ÿค”

haughty turtle
#

@leaden perch if you have a question just ask, someone with knowledge in flask will answer

karmic egret
#

how do I get over the original template , and set up my own template for login, logout, etc in flask security

#

I mean I did not set up any route yet in my program,

#

yet this page can show up

past cipher
#

you must of already created that page

#

and why use flask-security

#

why not flask login ?

#

@karmic egret

karmic egret
#

@past cipher What is the major difference between flask security and flask login

#

Because my teacher suggest me to us flask security

past cipher
#

security is dead I believe unless its started being maintained again

karmic egret
#

okay, thanks

rancid lintel
#

I'm planning on creating a web crawler that collects new posts from my favorite blogs and returns the response in a JSON format. I'm familiar with how Django rest frameworks work so I decided to proceed with it. My problem is though how can I call a web crawler from an API with a post request?

compact crest
#

Hi all I have a question if you could help me, i'm trying to sort a column by images in Wordpress (Tablepress) but i don't know how to do it, any idea?

karmic egret
#

I figure out that you can also use the session in flask to build a login in system. What is the difference between this and using flask login library

lavish prismBOT
#
Bad argument

Converting to "int" failed for parameter "pep_number".

native tide
#

oops

#

hey guys, I want to know that if the logic in that jinja syntax I applied is right or not?

past cipher
native tide
#

it's no working

#

nvm I wanted to paste it in hastebin

past cipher
#

have you tried doing the loop in python and seeing if it works

#

on backend

native tide
#

yeah

#

no

#

I mean I tried the for loop logic separately and it works

#

but idk how to implement it in jinja

past cipher
#

it looks correct

native tide
#

oh

#

wait

karmic egret
#

and who can recommend me some starter article flask login

#

because I am still new to the library

native tide
#

Can someone help me out with a feature in Django? I wanted to implement a so called "save for later" or "pins" feature to my blogs app that will save that post from that user and display it to a specific template called "pins" (just like on instagram, the save button). I'd appreciate it, thanks!

past cipher
#

store the post id in the database and then call it on the saved later page

#

a

#

@native tide

native tide
#

hello

#

hi

#

I am doing a django project and I'm trying to override template and static folders, I encountered an error

#

@native tide wanna hear?

#

no

#

idk

#

about django

#

oh

#

i'm a beginner

#

I have a problem, you wanna hear?

#

let me see

#

I want a list (probably) of dates from the day covid started cuz i'm making a covid-tracker app (flask)
rn it only lists latest updates

#

it's a very basic app

#

I want to make a drop down menu from where we can see cases for a specific date

#

I think I can get the date by performing a requests on this link

#

@native tide ?

#

yeah show me the dictionary (json) data

#

yeah

#

I pasted it on hastebin

#

I see

#

how about you re read the documentation

#

api doc

#

ohk

#

o