#web-development

2 messages · Page 200 of 1

golden bone
#

Your web app could incorporate an API, if you design it to

rigid anvil
dense slate
#

Does the service require you authorize certain IPs?

#

Or maybe an environmental variable isn't set correctly in prod?

rigid anvil
#

idk

#

i think pythonanywhere might just not accept o365 smtp

rare quiver
#

hello, I am working making a web application with flask, I am trying to make a graph with chart.js, I am really new to js but I am not sure what I am doing wrong here

https://paste.pythondiscord.com/acetayijol.xml

the graphs should be going in the spaces

glacial yoke
#

Hey everyone, I am deploying my django site using nginx and gunicorn. I am using this repository called django-social-auth-app which allows the user to login using any other third party apps or social media. In my gunicorn config I bind it to the localhost IP:127.0.0.1:8001, on which of course nginx is listening. So therefore whenever I go to the machine's IP, I can see the site, and everything works.
But the problem is, that when logging in using the above stated repository, after having logged in, and when it redirects you back to the site page, it redirects the user to 127.0.0.1:8001, and not the machine's IP. I tried binding gunicorn to the actual machine IP, but that breaks all the other functions that depend on the server IP (e.g. websockets, api requests, etc...), and also it is really not the best thing to do.
If anyone has ever faced some issue like this, can you please help me?

native tide
#

or nginx

#

its django

#

that produces invalid redirect

glacial yoke
#

yeah, ik that it has something to do with the repository, which is what I am trying to work out rn

native tide
#

is that repo public?

glacial yoke
#

It's like the biggest social auth repo for python

#

You can use it on either flask, django or anything else literally

#

I have tried to change the login_url and redirect_url settings which the repo provides, but it didn't help

native tide
#

can you link the repo

dense slate
#

I've used that repo and I don't remember setting anything outside of Django to make it work.

#

It should hit an endpoint in your backend that then redirects wherever you want it to.

#

@glacial yoke

glacial yoke
#

So it’s something with the redirect uri

#

Which is what I’m trying to figure out rn

#

ok, I fixed it

#

In the end I had to change all the SOCIAL_AUTH settings to redirect to my server's IP

#

I also had to add my server IP to the redirect_uri's

#

then I added a few proxy settings into my nginx config, and it all worked

raw field
#

Is django good for a microservice setup? My goal is to develop multiple tools to use for my personal game studio including:
User registration (via api, or via website)
User authentication (using Json webtokens or OAuth2.0)
Matchmaking service usinng buckets and websockets
Metadata server (holds server information, player counts, locations of datacenters...etc)

#

I've been reading mixed information online where people just give their opinions, but I'm looking for a legitimate answer, not just opinions.

golden bone
#

Unless you can specify what factual information you are seeking, you're only likely to get more opinions here. "Is Django good..." is inherently a question of opinion. What does "good" objectively mean to you here, and what you are comparing it to?

If you're asking whether it is normal to use Django for the tasks you have listed, yes it is. If you're going to build a site with all those features using a Python framework, Django is the obvious choice. What else would you use?

inland oak
# raw field Is django good for a microservice setup? My goal is to develop multiple tools to...

Surely. Django works the best for your voiced goals in a Django Rest Framework setup
https://www.django-rest-framework.org/
Django will provide the FASTEST development.

The only disadvantage of django, of not working fully in async, which can be probably fixed in next version. Partial async support is still there though, just Django ORM is still sync. But really.... async is often not even needed in most of cases.
Even for async Django can work though. Django channels is an example of Async oriented Django to implement chat.

For pure async setup, fastapi is better.

raw field
#

Django has a lot of stuff right out of the box, I have no interest in building my own user registration system, Django Admin basically has that right from the beginning.

inland oak
# raw field Does FastAPI have the same amount of functionality as Django?

Different amount of functionality.
in FastAPI you are going to setup ORM on your own, SQL Alchemy or whatever is your choice.
But FastAPI brings A LOT of out of the box too. For example auto generated interactive wiki for your REST API. Open API or smth like that. Fast API just brings different stuff out of the box

raw field
#

The only thing I worry is if this game I'm working on were to scale up, I worry that having a completely synchronous ORM could be devastatingly bad long term.

inland oak
# raw field Ah I see

FastAPI has some sort of quirks with enforcing good static typing i think. That's one of the advantageous of it that enforces better quality. I heard only rumors about FastAPI, I worked closely only with Django.

raw field
#

Honestly though, I imagine it wouldn't be that difficult to just simply treat each Django 'app' as a separate microservice and then as for the ORM part, couldn't you just run each completely indiviudally?

#

Like I imagine you could just copy + paste the base directory + the app you want to a new machine and do that

inland oak
inland oak
lament charm
#

quick question. Should I be using status code 404 or 401 for failed login attempts?

#

user not found/wrong password

inland oak
lament charm
#

that's the one I was leaning towards, thanks

raw field
#

Lol

inland oak
inland oak
# lament charm that's the one I was leaning towards, thanks

Some people choose to return just general error "Login or password is wrong", that prevents hackers from web scrapping correct logins/emails.
with having different errors, you could confirm them existing emails for scrapping emails or reducing difficulty to crack

inland oak
lament charm
raw field
#

i still dont mind server side rendering of views

#

im not willing to buy in on these front-end frameworks yet

#

like Vue and stuff

inland oak
#

hehe. I dived into Vue.js, it is awesome

raw field
#

It's just not where I need to be right now

#

I'm trying to make a game, not a website lol

inland oak
#

hardly seeing how you are going to make a game properly without reactivity that bring frontend frameworks.
I suspect you are going to reinvent the wheel in going vanila js and remaking poorly some frontend framework.

#

web games usually involve a lot of client side interactions

raw field
#

I'm planning on using the website to store player data, authenticate users...etc

inland oak
#

oh, so the game is for Windows platform then

raw field
#

Well for now yes, but I have experience on consoles

#

I've used PS5 dev kit and my co-founder has experience with the ps4 dev kit

#

But we need licenses to use them sadly

inland oak
#

What's your language

#

for the game

raw field
#

What do you mean?

inland oak
#

programming language for the windows app?

raw field
#

C++

viscid spade
dusty moon
#

I got a weird question…. It’s about code (not Python code), but not exactly.
I’m learning JavaScript from W3Schools. Starting the tutorial or guide or whatever it’s called, they show a little bit on how to change elements on the page, and then go ahead and teach about variables and stuff…

I wondered if I can learn the stuff that really changes the page before I learn about the more technical stuff.
Will I get confused, or it’s okay for me to do that?

#

I want to start with these thing

inland oak
dusty moon
#

That book looks really old school 😄

inland oak
#

It is really good one 😉 It helps to understand mechanics behind javascript

dusty moon
#

I see.

inland oak
#

like... javascript implements half of other programmings languages concepts with just a different application of functions...

#

I don't see how it is possible to learn it without it

dusty moon
#

So I’ll just start with technical stuff (variables and stuff) and then have fun with the html stuff

#

?

dusty moon
#

I see. Well, that’s all I needed. Thank you!

royal dragon
#

subscibe my chenel

#

||please like and subscibe my chennell||

#

click only humans not bot

native tide
digital hinge
#

Has anyone made or know of a start.me or iGoogle clone with python in flask?

grizzled basin
#

Anyone familiar with using celery with a docker container?

rigid anvil
#

Hello I have created a voting site to vote for some merch designs for my school, but it doesn't work on some apple products (some variables are passed wrongly or changed of value) does someone know why could that be occuring? Its a flask python web app

dense slate
dense slate
rigid anvil
#

When I have more info I'll come back then

native tide
#

does JavaScript .length on a variable with [[x, y] [z,k]] return 2 or 4

dense slate
#

[0].length would measure the first array inside

solar obsidian
#
        <form method="post">
          <label class="switch">
              <input type="checkbox" name="cumulative" {{cumulative}}>
              <span class="slider round"></span>
          </label>
        </form>``` how do i post it
solar obsidian
#

i wanna update a db and make it input on or off in the db when the flip the switch

#

im trying to figure out how to run the code when a user interacts with the switches

dense slate
#

You need to use something like ajax if you're doing it from the html.

#

If you want it to update based on the DB.

#

You can just simply post it to the view and cause a css change without waiting for a return from the view though, which is probably better. So it only has to check the DB on a page refresh.

solar obsidian
#

im using flask

#

i should be able to do

#

something like

#

if request.method == "POST"

#

then it can see what the values are

#

which will then run code

dense slate
#

Ok, sounds good.

solar obsidian
#

ok but why isn't it posting

random sand
#

show code again

dense slate
#

What's the view look like

random sand
#

if you use request.args then change it to request.forms

solar obsidian
# random sand show code again
        <form method="POST">
          <label class="switch">
                <input type="checkbox" name="cumulative" {{cumulative}}>
                <span class="slider round"></span>
          </label>
        </form>```
#

flask should say tho if it posts

#

even if i dont have the correct code to handle the post

dense slate
#

Don't you need javascript for it to post onClick?

#

How else does it know to submit to the view?

indigo kettle
#

you need a button with type=submit to submit the form

dense slate
#

its a checkbox

#

he wants it to submit when it changes

#

I just don't think that can be done without an ajax call unless you're ok with the page refreshing after it submits.

slow compass
#

hi everyone, what do I need to know to write a django website, other than django itself and html?

native tide
rigid anvil
inland oak
grizzled basin
#

any pointers to this?

#

I'm bashing my head, I've put celery same container as the fastapi app, but that's not a good workaround

inland oak
#

Obviously with raising rabbit first

grizzled basin
inland oak
#

It should check report that it connects to rabbit

grizzled basin
#

yes it connects to rabbit

inland oak
#

U can manually connect to rabbit and check all values inside

grizzled basin
#

otherwise I wouldn't be able to use celery container in local app

inland oak
#

Hmm

grizzled basin
#

the problem is on syncing

#

not related to rabbitmq

inland oak
#

Shrugs. I had detailed enough errors to debug it

#

Plus I worked in Django.

grizzled basin
#

"If I start the webapp locally on my computer, and don't start the padel-checker-web-1 container and only use the other 3, celery on docker syncs with it and works."

#

but it's not a framework issue, if you observe the last img of that post

#

I'm just invoking celery on the container

#

and it just hangs

inland oak
#

Hmm

grizzled basin
#

so it has to be some kind of problem in communication between containers, that's my guess

#

because "outside" if I use my IDE to use that celery instance, it works fine

inland oak
#

Actually yeah, the celery code is almost not touching framework at all.

So framework is not issue

#

Anyway ...

#

First request all values inside rabbitmq, to confirm it did not write info it

Then I guess just debug your celery code, some issue there

grizzled basin
#

How is that problem in my code if it works outside docker :d

inland oak
#

Worker reports which tasks it discover, perhaps it is not seeing it

inland oak
grizzled basin
#

environment:
- C_FORCE_ROOT=1

#

I'm even using this

#

it's a docker issue, but I'm not a pro in docker, so I can't get where's the problem

#

flower works, celery connects to rabbit, rabbit works, web app does not work

inland oak
#

Hard to say, I used redis instead of rabbit 🤷‍♂️

grizzled basin
#

ok ty anyway

inland oak
#

Plus I did it without compose

#

Because I wished deploying them to different servers

#

For better worker scaling

#

Although I did it with compose in the past

#

I can give u my old compose for this

grizzled basin
#

yeah if you have celery + sth

#

I can look to see if I'm missing something

inland oak
# grizzled basin I can look to see if I'm missing something
version: '3.8'
services:

  web:
    build:
      context: .
      dockerfile: dockerfile
    volumes:
      - static_volume:/app/web/build/static
    expose:
      - 8000
    env_file:
      - ./.env.${mode}
    depends_on: 
      - redis
    
  nginx:
    build: ./nginx
    volumes:
      - static_volume:/app/web/build/static
      - ./ssl:/app/web/ssl
    ports:
      - 5555:4000
    depends_on:
      - web

  # celery
  redis:
    image: "redis:alpine"
    expose:
    - 6379
    volumes:
    - ./redis/redis.conf:/usr/local/etc/redis/redis.conf

  celery-worker:
    build: .
    command: celery -A core worker -l INFO
    env_file:
      - ./.env.${mode}
    depends_on: 
      - web
      - redis

  celery-beat:
    build: .
    command: celery -A core beat -l INFO
    env_file:
      - ./.env.${mode}
    depends_on: 
      - web
      - celery-worker
      - redis
volumes:
  static_volume:
  static-content:

I guess it is not really useful for your case, or may be it is?

#

anyway the best is auto generator of cycling tasks. I used it instead of cron in this case

#

u don't need the beat

grizzled basin
#

I'm actually using something on fastapi to repeat tasks

#

Not using anyhing like beat or cron

#

@app.on_event("startup")
@repeat_every(seconds=60) # 1 minute
async def fetch_data() -> None:

#

for example

inland oak
#

heh

#

my silly old compose had too many values hard coded 😉 Although since it is compose, it is not an issue

#

because compose stuff uses relative service name addressed links anyway

#

so there was no point to dehardcode the links

grizzled basin
#

yeah

solar obsidian
#

if so ima make it a pop up on the bottom of the screen

tepid lark
#

maybe a long shot, but is anyone familiar with an audit log framework for python/django?

grizzled basin
tepid lark
#

something focused around the view level rather than the orm, because half of what I'm doing is using django as the frontend and talking to other non-dbms systems

grizzled basin
#

I've put depends_on web

#

and now works

#

lmao

inland oak
#

I am deploying them all independently to different servers without any order and it is all fine

grizzled basin
#

dunno, now it works. It's weird indeed

native tide
#

please

#

any Js / apps script god

#

my monkey brain just cant it wont work

solar obsidian
#

i give up on the toggle switch

#

someone just make me a button that when i press it posts and toggles

#

like a check box

#

but without having to click on the check box and then click submit

solar obsidian
#

i cannot find anywhere how to do it

native tide
#

I am trying to make an assignment organizer, in this assignment organizer, I have an app called calendar which has a model events, I have google authentication. I added a method to add events but each event shows up even when logged into different accounts. How can I fix this

solar obsidian
#

i found out my problem is it only posts if i have a submit button

#

how can i automatically submit

dense slate
solar obsidian
#

or post without it

dense slate
#

But it's up to you.

solar obsidian
#

i see it

#

onClick

#

but how do i make it work with the switch

dense slate
dense slate
#

That's the logic. How to implement it, that you'll have to try to figure out first and we can help you when you're stuck.

dense slate
native tide
#

give me one second, I'll show you the views.py for the model

lavish prismBOT
#

Hey @native tide!

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

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

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

https://paste.pythondiscord.com

dense slate
#

Just show me the view for the one template, not all of them.

native tide
#

what do you mean?

dense slate
#

This is a web or mobile app?

native tide
#

web app

dense slate
#

What framework?

native tide
#

django

dense slate
#

Ok, so your view controls what you see on the page, yea?

native tide
#

yeah

dense slate
#

So show me the view that controls the page with the posts you want to change.

#

Where you query your database for the events.

native tide
#

here you go:

#
def event(request, event_id=None):
    instance = Event()
    if event_id:
        instance = get_object_or_404(Event, pk=event_id)
    else:
        instance = Event()
    
    form = EventForm(request.POST or None, instance=instance)
    if request.POST and form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse('calendarApp:calendar'))
    return render(request, 'cal/event.html', {'form': form}) 
dense slate
#

This doesn't display events on your page.

#

This gets one event and displays the details it looks like - and submits them.

#

Is your problem that you are displaying events for all users on a page, and you want only to show events that the user created?

native tide
#

yeah

dense slate
#

So where is the view that gets all the events?

#

and returns them to your template

native tide
#

give me one second to locate it, I forgot where I put it

#

@dense slate would it be in the views.py of the calendar app itself? or would it be in another file

dense slate
#

Do you know how views work generally?

#

You go to a page of your app website, and then the request is sent to your Django backend to figure out what data to show on the template. This is called your view.

#

So the view asks the DB for data based on what you want, and then you return it to the template, right?

native tide
#

this is my first time working with django in 5 years so I've forgotten essentially everything sorry

dense slate
#

It's ok, I'm just trying to teach you a bit along the way.

#

So you understand how it works. 🙂

native tide
#

I actually think this was present in my utils.py

#
from datetime import datetime, timedelta
from calendar import HTMLCalendar
from .models import Event

class Calendar(HTMLCalendar):
    def __init__(self, year=None, month=None):
        self.year = year
        self.month = month
        super(Calendar, self).__init__()

    # formats a day as a td
    # filter events by day
    def formatday(self, day, events):
        events_per_day = events.filter(start_time__day=day)
        d = ''
        for event in events_per_day:
            d += f'<li> {event.get_html_url} </li>'

        if day != 0:
            return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>"
        return '<td></td>'

    # formats a week as a tr
    def formatweek(self, theweek, events):
        week = ''
        for d, weekday in theweek:
            week += self.formatday(d, events)
        return f'<tr> {week} </tr>'

    # formats a month as a table
    # filter events by year and month
    def formatmonth(self, withyear=True):
        events = Event.objects.filter(start_time__year=self.year, start_time__month=self.month)

        cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n'
        cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n'
        cal += f'{self.formatweekheader()}\n'
        for week in self.monthdays2calendar(self.year, self.month):
            cal += f'{self.formatweek(week, events)}\n'
        return cal
#

so in the events_per_day we should be filtering by user as well

#

but what exact command would do this

#

I tried this and got the error: Calendar has no attribute request

random sand
#

So what is that you wanna make?

native tide
#

I want to make a assignment organizer, part of the assignment organizer includes a calendar feature and google authentication. In the calendar feature I want then to create and display events, but then even if I am logged into a different account, it shows events created by other users

random sand
#

ok

native tide
#

@random sand as you see in the utils.py above, when I add events to the calendar, I only filter by day, how do I filter by event

#

not by event sorry, I mean by user

random sand
#

write something user.filter()?

#

i am not sure

#

tho

dense slate
#

So it won't have a request attribute. Request is a parameter passed from the webpage/template to the view.

#

You have to somehow list the events where request.user = event.user

#

like events.objects.filter(event.user=request.user)

native tide
#
from django.db import models
from django.urls import reverse

class Event(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    @property
    def get_html_url(self):
        url = reverse('calendarApp:event_edit', args=(self.id,))
        return f'<a href="{url}"> {self.title} </a>'
#

this is the event model, do I have to add a user field

#

and how would I automatically initialize it to the current signed in user

dense slate
#

Yea, events should have an author/user field that is a ForeignKey field that points to the user row.

#

What do you mean by automatically initialize?

native tide
#

never mind about that, I think I was wrong all along

#

it's like when you hit submit to add the event to the calendar, we initialize an event object and we set the author field =user.uid

dense slate
#

Yea, that's what should happen.

#

or author=request.user

native tide
#

would request.user work?

#

for google auth

dense slate
#

That's really vague. It depends how you use it.

#

request.user will work in your views.

#

def myview(request):
etc...

native tide
# dense slate def myview(request): etc...
def event(request, event_id=None):
    instance = Event()
    if event_id:
        instance = get_object_or_404(Event, pk=event_id)
    else:
        instance = Event()
    
    form = EventForm(request.POST or None, instance=instance)
    if request.POST and form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse('calendarApp:calendar'))
    return render(request, 'cal/event.html', {'form': form}) 

#

so now we just set form.author=request.user

#

right after we declare form

teal matrix
#

Hi there, how would I be able to send my javascript variable in HTML through to to python to be used? Thank you

native tide
native tide
solar obsidian
native tide
native tide
#

@dense slate for the foreign key, we would have to access the social accounts model, how would we do this?

native tide
keen ermine
#

Hello, guys

#

Has any of you ever used Pub/Sub architecture with Python?

dense slate
dense slate
#

It's an async call from your front-end so that you can do something without refreshing the page.

#

If you update without it, you will have to do a page refresh.

dense slate
native tide
native tide
dense slate
#

Yea I don't know man, you're asking some big questions without me seeing any code so I can only speak in theory at this point.

#

When you ask a social auth api for a login, it sends you information back. Like a refresh token, etc.

#

You have to do stuff with that on your end to make it work with your app.

native tide
#

ok so for example we have to do this to retreive a social account

#

user.social_auth.get(provider='facebook')

#

in our case, it's google

#

but where would I call this

dense slate
#

If you press "login from google" on your website, I think it has to go directly to a social auth link that you get from the API. That API should be setup to then send a return response to your backend endpoint.

#

Either that, or the button activates a view on your backend, where you call whatever function that is you wrote.

#

The library you're using as your social auth should have documentation on how to set this up.

native tide
#

ok I think I Just got it working thanks!

dense slate
#

Sweet. 🙂

sacred crane
#

I was trying to do an inference of a PyTorch model using django rest API. I am new to django rest api. can anyone share some resources are suggest me how to do it if anyone worked before on the same problem. Previouly i used django api and did inference by keeping all the pytorch code in views.py but now i saw the same thing done on models.py while using rest framework and using axios.js and corsheaders I am pretty confused.

native tide
#

Will anyone test my flask code

native tide
#

Ok

native tide
#

@inland oak but my code is genuine and working as html

#

And no problem with flask at all it is running but doesn't get desired output

#

@inland oak

inland oak
#

read about all types of testing, and cover the code.

#

otherwise it is just a ... guessing where it went wrong

#

for frontend things, u can test in python at least with selenium.

native tide
#

Ok

native tide
#

Apps Script (JS)

how the fuck do I find a cell by date
.textFinder() doesn't work
tried finding by unix, also doesn't work

#

spent few hours yesterday I'm hopeless at this point

inland oak
# native tide Apps Script (JS) how the fuck do I find a cell by date .textFinder() doesn't wo...

googling "javascript find in array by date" and opening links
https://stackoverflow.com/questions/27450867/how-to-correctly-use-javascript-indexof-in-a-date-array

For more help with googling, provide bigger code example

native tide
#

lmao

native tide
#

@inland oak I done testing and the code is genuine I think there is a problem with blocks can you check it

native tide
#

{%block content%}
and endblock

#

@Darkwind#7896

#

@inland oak

inland oak
sacred crane
#

TypeError
TypeError: 'method' object is not subscriptable getting this error when running flask need help

#
response = {}
@app.route('/predict', methods=["POST", "GET"])
def predict():
    if request.method=='POST':
        solute = request.form["solute"]
        solvent = request.form["solvent"]

    else:
        solute = request.args.get["solute"]
        solvent = request.args.get["solvent"]


    results = predictions(solute, solvent)
    response["predictions"] = results
    return flask.jsonify(response)
#

http://127.0.0.1:3000/predict?solute='CC(C)(C)Br'?solvent = 'CC(C)(C)O' using this url to see the prediction in json format

#

please help i have tried but i am unable to figure out where i am doing wrong for long time

grizzled basin
#

on request.args.get["solute"]

#

(and solvent ofc)

sacred crane
#

Now I am getting this error.

sacred crane
#

my inputs are # solute='CC(C)(C)Br'

solvent = 'CC(C)(C)O'

grizzled basin
#

I've never used boost python

#

but if you want to pass multiple args in the get, you use &

#

like this

#

@sacred crane

sacred crane
#

@grizzled basin Thanks now i am getting serialization error

grizzled basin
#

Your response probably isn't something serializable, like a dict

#

can you print me your response?

#

or try something like this:

return flask.jsonify({'result': response})
#

But I think you have to convert Tensor data to a serializable form probably

sacred crane
#

response["predictions"] = str(results) adding str() here resolved the problem

grizzled basin
#

what is the output of predictions(solute, solvent)

#

ok, cool

sacred crane
#

But it is returing tensor. How can i turn it into a float?

grizzled basin
#

yeah that's why str won't work

sacred crane
#

I am planning to use this result to show in a react website

grizzled basin
#

You have to find a way to serialize your torch obj

#

do:

print(results)
print(type(results))
#

and show me the output

#

you can hook this piece before the response

#
serialized_results = {k: v.item() for k, v in results.items()}
return flask.jsonify({'predictions': serialized_results})
#

try this

#

@sacred crane

sacred crane
#
tensor([[-3.4333]], grad_fn=<AddmmBackward>)
<class 'torch.Tensor'>
#

@grizzled basin adding results.item() solved the problem i guess

#
tensor([[-3.4333]], grad_fn=<AddmmBackward>)
<class 'float'>
grizzled basin
#

@sacred crane good!

mild wing
#

Hey, I'm looking to build an e commerce site, using django. Just looking to get the general gist and what I need to learn before, I want to make it so it's easy to add products from a UI, meaning that a user can add pages of html/products without actually doing html or any of that. Anyone got recommendations to some info related to doing that? Not sure if this kind of thing got like a name

golden bone
# mild wing Hey, I'm looking to build an e commerce site, using django. Just looking to get...
GitHub

An e-commerce website built with Django. Contribute to justdjango/django-ecommerce development by creating an account on GitHub.

freeCodeCamp.org

Learn how to build an e-commerce website with Django and Python in this full course from JustDjango You will learn all the steps for developing a complete e-commerce site, including: Setup and project configurationAdding items to a cartImproving the UICreating an order summaryThe checkout processHandling payments with StripeDiscount codesManagin...

wise kite
#

NEED HELP - Each time someone send request to my application i have to check their token with a yaml file in server. So i have to load that ymal file each time someone send request. Can i do something where I don't have to read that yaml file each time. Insted maybe django can load it one time in starting and Store that token into a veriable. And keep updating that veriable every 10 to 15 min from yaml file. ?

native tide
#

@wise kite I can help if it is flask

wise kite
#

It,s django. But solution should be kind of same bhai . Isn't it ?.

native tide
#

is it possible to change my maintenance page from an ip whitelist and htaccess to a login form

#

alot of people dont trust givign there ip addresses to get past it and i want the page to have a login form to bypass the page

dense slate
#

Rather than keeping the token in the DB.

wise kite
dense slate
#

What framework are you using?

#

Because you shouldn't have to restart the server just because you update the DB.

#

If you load the yaml file once at build time, and then need to change it, you'll have to restart the server to re-read it each time you change it.

wise kite
# dense slate What framework are you using?

Django. I might not. But my senior dev is Java dev he don't know anything about django. He said i have to do it that way . So i have to. It will be convenient for him i guess.

dense slate
#

Wish I knew what to say in that case. I don't really do a lot with direct file accessing.

#

Maybe using something like SQLite?

#

I think that saves as text if I'm not mistaken.

vapid stag
#

I have a 25 lines of story displayed in a webpage. One user can select a word/number/symbol or anything in that page with their mouse select.

can I get:

  • the word itself
  • the line number
    -index number
    To my backend flask app?

Which approach should I take?
Thank you!😊

#

One can upload a story file, he/she can select a word or anything from what's displayed on the screen. To the backend, we should get index number, line number

inland oak
#

The point of Django of having easy database management with its ORM

#

if you aren't using it... u aren't using Django

#

Reinventing the wheel with going for YML stored self written database is just plainly horrible

#

it is fine to use YML for one time setting up settings from the code though

jolly obsidian
#

Anyone here know any website where we can get the Time complexities by entering the code?

inland oak
#

Going full Vue.js, loving its ecosystem

#

Like... everywhere just using flex boxes ;b they are fine to remove almost any positional problem ;b, since they allow nesting.

#

Interested to go through Service Worker mastery game too though 🤔

#

Because u know... it looks like cool stuff to have

#

That music.... when playing flex zombies. Makes u writing layout code as super easy. You remember how your life was depending on it!
I needed to write syntax fast enough to aim my crossbow and kill the zombies!

#

Awesome game

dense slate
#

Interesting I've never seen that.

inland oak
#

Epic level of quality game 😉

#

After this game u'll remember the syntax as your reflexes

dense slate
inland oak
#

not having enough knowledge to compare. I can say that Vue has state management easily out of the box, which is simple to use.

dense slate
#

Global state or just state?

inland oak
#

for global state I mean

wise kite
inland oak
#

for local state, in one component everything is easy and simple

#

we have there static JS things, computed JS things and some custom things I think.
Vue gives easy reactivity to any data, and allows easily to setup reactivity in both directions between rendered and JS data

#

Component writing is easy, just create another file with Html, Script and Style section.

#

Vue is mostly not interfering into Html code too much

#

It has Django/Jinja like syntax for inserting data into Html, with exception to binding Properties and writing loops, which has more HTMLish looking syntax

#

{{ here we have full javascript language compatibility to insert data }}

#

I don't know react to tell you differencies, but Vue is nice and easy to use and learn 😉

#

Setting up I18N is easy too, going out of the box

#

out of the box, I can have everything, even examples how to write unit and e2e tests

#

btw, I love SASS. SASS is Awesome

#

I did not reach that section, but Vue is also bringing some of its own addition to have more features to CSS animation I think.

inland oak
dense slate
#

I'm curious how you handle caching in the future. I've never used redis so I cache everything on the front-end with Next/Apollo for a big speed boost.

#

Yes I've seen that as well.

inland oak
#

I have 3 weeks to implement my project at least, purely for frontend

#

or more, considering requests to setup Payment system, and monitoring+logging requested things to monitor business stuff

#

during those weeks going to become intimately familiar with Vue

dense slate
#

I'm wondering if using redis can actually get an even better speed boost in addition to FE caching.

inland oak
#

I used redis only in backend framework

#

I can say that it is needed only for framework level logic to cache stuff from database for example

#

but I think it would be much faster to use...

#

Nginx/Traeffic as web accelerators, they will provide caching copy BEFORE request reaches the framework (when we set them up as reverse proxy to our backends)

#

I think that's faster ;b

#

no idea about how the same stuff is handled in frontend yet. Except for knowing about browser storage existence and cookies 🤷‍♂️

#

Fascinating. I am using JUST A FRACTION of flexbox powers!

native tide
native tide
#

heroku

indigo kettle
#

did you try to look at the logs

sharp bronze
#

does anyone have experience with streamlit?

#

for some reason everytime I click on a st.number_input to put in a number my app just goes blank

native tide
eternal blade
#

In django-channels is it possible to add jwt authentication?
I'm using django-rest-framework-simplejwt and is it possible to implement jwt authentication when a user is connecting to a consumer? won't sending the token in the query string have security issues?

dense slate
#

Why would it have security issues?

wooden ruin
#

I'm not sure if it's worth learning or just sticking with nuxt 2

fair birch
#

Hey, I'm having trouble integrating a S3 storage on my django project (i'm using jschneier's django-storages ). I want to manipulate the Content Disposition metadata to ease my backups (I want to write them using a UUID as filename, but populate the contentdisposition filename so users can download it with a friendly name). I've opened a question with more details at #help-rice

dense slate
#

@inland oak Sounds like redis will be good to cache server-side even if you use client side caching when you have a high number of users:
Client side caching improves the performance for the clients. But if the number of clients is high, you can experience high load on the server side resources which will eventually affect the client side performance too.
Makes sense.

solar obsidian
#
    if request.method == 'POST':
        print(request)
        return "success"```
#

ok so

#

uhhh

#

why does the request only look like this

#

<Request 'http://127.0.0.1:5000/dashboard/880574219560321104/api' [POST]>

#

how do i get the data

solar obsidian
#

nvm, i got it

sacred crane
#

Below is the code used to fetch the rest API predictions in react app.

function App() {
  const [state, setState] = useState([{}]);

  useEffect(() => {
    fetch("/predict?solute=CC(C)(C)Br&solvent=CC(C)(C)O")
      .then((res) => res.json())
      .then((data) => {
        setState(data);
        console.log(data);
      });
  }, []);

In fetch /predict?solute=CC(C)(C)Br&solvent=CC(C)(C)O here solute=CC(C)(C)Br and solvent=CC(C)(C)O are the inputs for the flask rest API to give predictions.

But I want to give it from the frontend rather than mentioned in the URL. How to do it?

native tide
#

is this django?

#

idk django

#

i only know html css java script

pallid lily
#

this is Javascript React

trail veldt
#

Hello!
I'm developing a Flask app, and I'm a beginner in this. So here is my script:

from flask import Flask,render_template,request

app = Flask('')

@app.route('/')
def home():
    return "Hello World"

@app.route("/test",methods=["GET","POST"])
def test():
    if request.method == "POST":
       # getting input with name = fname in HTML form
       inp = request.form.get("testinput")
       # desc = request.form.get("desc")
       # getting input with name = lname in HTML form 
       return "Test input: "+inp
    return render_template("testing.html")
``` And my testing.html
```html
<!DOCTYPE html>
<html>
    <head>
        <title>Testing</title></head>
    <body>
        <h1>Hello there</h1>
        <form action="{{url_for('test')}}" method="POST" id="tst"
            <label for="testinput">Input: </label>
            <input type="text" name="testinput"> <br>
            <button name="gennew">New input</button>
            <button type="submit">Submit</button>
        </form>
    </body>
</html>
``` But I want when I click gennew button, it will create a new entry right down this button. How can I do that?
inland oak
trail veldt
#

Um, I just want when I click the button and then an input being inserted right after it in the browser, and later I can access it too 😄

inland oak
# trail veldt Temporally in user browser

They I would say that u use wrong tool for that ;b
Flask is not meant for this. React / Vue.js will work much better.
You can still do it in Flask it though, but u will need working with Vanilla JS. At least if you wish the data being shown without page re render;

We can simplify things a lot your syntax writing in Flask for this purpose, at the cost of sacrificing time to update the page 🤔
Mm... all right, so in order to do this simply in flask... We should probably use Cookies! They will allow you to use relatively easy client side storage while accessing easily as server

#

Lets write pseudo code how it will looks like...

#
Client side form
Pressing button => Invoking POST request with new value

Server receives piece from POST request data
Checks user cookies
Combined result rendered back, with attaching updated cookie to client
#

yeah, it would be simpliest way to do that if we have Flask (at the cost of having requests to server every time with re rendering page every time we press button)

#

more complicated (and a bit ancient) approach would be to use Vanilla JS in order to do that without additional requests to server, manipulating user DOM purely client side
more modern solution would be to use frontend framework

trail veldt
#

But how can I... get and use the cookies using Flask?

#

And what is Vanilla.js

chilly bridge
#

How do I run a piece of Python code when a button on my website is clicked? I'm using Flask.py and failed to find the answer elsewhere.

#

I don't think you should post this here. #game-development would be a better place. I'm not a moderator so feel free to do whatever you want.

inland oak
#
@app.route('/')
def index():
    resp = make_response(render_template(...))
    resp.set_cookie('somecookiename', 'I am cookie')
    return resp 
# This way cookie will generate in your browser but you can get this cookie in next request.

@app.route('/get-cookie/')
def get_cookie():
    username = request.cookies.get('somecookiename')
trail veldt
#

great thanks

#

But how about user decline the browser to use cookie(s)?

inland oak
# trail veldt And what is Vanilla.js

it is regular Javascript, that is used to manipulate browser DOM
https://www.youtube.com/watch?v=cuHDQhDhvPE
See for yourself difference in how to do the same with Vanilla JS or with frontend frameworks

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

they just decline interactive agreement at some specific web site, it is purely your logic, not theirs

#

some users erase their cookies after browser is closed though, but it will not prevent you from making your functionality

#

@trail veldt actually the video shows exactly what you wished to make 😉 adding entries with button and input
See for yourself how it is done in Vanila JS and other frontend frameworks

trail veldt
inland oak
#

according to their rules web site should ask and explain why they track user with cookies

#

you see, cookies can be used for evil... for tracking you for advertisements and etc

native tide
#
2021-11-11T08:27:10.802264+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=POST path="xxx
" host=xxxx-xxxx request_id=c0aee3b4-67f2-410c-af70-c00d747257d5 fwd="156.211.170.33" dyno=web.1 connect=0ms service=30204ms status=503 bytes=0 protocol=https```
**this is a heroku logs whin i upload a file .zip or . rar  it says like this in the image**
#

help plz

inland oak
native tide
#

okay !!

#

so help

native tide
#

deploy a website?

native tide
#

no i deployed the website but i have a field file field i but a file in it it gives me this err

native tide
inland oak
inland oak
#

..instead of using cookies, you could have been using query params to accumulate the data (basically in user url)
url/?data=stuff&anotherdata=stuff
it could have been used for your case in the same way. A bit awkward way tbh, but who judges.

#

but cookies I guess should be more comfortable.

rigid loom
#

We don't allow recruitment here, as per our #rules

eternal blade
lucid vine
sullen pebble
#

Is it possible to create a website using markdown with style formatting (hosted on github pages) ?

inland oak
inland oak
# sullen pebble how?

oh wait. I tell wrongly, I just commit directly to repostiroy my markdown pages, github/gitlab pages aren't even needed.

#

just writing markdown, and having relative links, they work fine in gitlab

sullen pebble
#

im talking abt creating a website

inland oak
#

what u assume being a website

chilly bridge
#

How do I run a piece of Python code when a button on my website is clicked? I'm using Flask.py and failed to find the answer elsewhere.

native tide
#

You can create a view, connect it to a URL and add this URL to your HTML form.

#

If you write more info on what you want to do, I can make a more detailed response.

austere raptor
#

Hi guys, Is there any channel I can post my latest work on?

chilly bridge
sullen pebble
inland oak
sullen pebble
#

something hosted on github pages

#

thats what i want

inland oak
#

🤷‍♂️ all right. So anything hosted in github pages, even text file will be website for you

vapid stag
#

I'm starting JavaScript. I'm confused thinking a better way to run it. My friends suggest to use Nodejs since I'm familiar with cmdline.

Other one said that I can run js in browser, by creating snippest inside chrome dev console. Although I don't understand what he meant, I think I really want to know this

#

Can we actually run Js inside a browser? Just like writing inside an interpreter

#

Vanilla js without html

#

Or nodejs would be better?

sullen pebble
#

like the background colour, font styles etc

#

afaik only html&css can do that

#

is it possible just to have an external.css and markdown for the content?

serene prawn
umbral rock
#

I'm trying to get started with Django and i'm a little confused about the overall structure of the project. I know that I should create an app for a blog for instance, or a forum, but should I create an app for my home page? Or do I just use the files that were created when I used startproject?

serene prawn
#

@umbral rock If you have some individual parts of your project that are not highly coupled you could split them into different applications

umbral rock
#

My plan is to first off create a homepage, then start to expand out by making a planner app, a blog app etc. I'm just a bit confused as to whether I create my homepage in my project folder or whether I should create an app for my homepage

serene prawn
#

It depends on what you mean by homepage in this case, if it's some sort of static landing page i'd make it separate app

umbral rock
#

Yeah, it's going to be static. Thanks 🙂

bronze palm
#

does anyone know some reference material for Django rest and taking in parameters? I can do it with regex and taking the full endpoint but I was wondering if there is a better method?

golden bone
dull isle
#

does anyone know how to use BeautifulSoup4 to parse html strings?
ping me if you've got the answer or you can point me in the right direction, thanks! 😄

dull isle
#

oh thanks!

sacred crane
#

How to rectify cors error

dense slate
#

I have my FE (next) and BE (Django) in separate directories on the same server. I'm trying to upload a file via GraphQL via the BE and have that file be saved in the public directory of my FE but I'm getting:
Detected path traversal attempt

There a way around this? I can only upload without an error if I upload to my media_root directory within the Django project. If I try to go above that level, I get this error.

inland oak
# sullen pebble how would i format it 😕

Well, besides markdown, there is really similar ReStructurizedText syntax.
You could use Python tool Sphinx
Which allows to write in this syntax...
...as for styles, you can choose at least a dozen of premade stylings which are available in the tool.
Perhaps more little adjustments to elements is possible.
But that's it.

#

And... actually you know.. if u don't want to deal with HTML and CSS
but u a wishing to have still relatively customizable thing capable to change background / fonts and e.t.c.... You are probably looking for WordPress.

indigo kettle
native tide
#

Can we get a domain for free

dense slate
sullen pebble
#

is 'jekyll' md?

inland oak
#

https://github.com/dd84ai/darkbot
Just copy folder sphinx from here (and requirements.txt with scripts.py file and scripts folder)
in project settings enable github pages from docs folder
install dependencies for sphinx (and click library) from requirements.txt

use python scripts.py sphinx build command in order to build your website to from source to docs folder
(or manually delete previous docs, create folder docs, make empty file .nojekyll in docs, and write command sphinx-build -b html sphinx/source docs)

change sphinx folder files to match your desired RST documents

#

this setup is silliest and dumbiest, because you need to commit your docs folder to repostiroy in order for this way github pages to work 😉

#

it can be made smarter with pipeline and artifacts, but whatever.

sullen pebble
#

well

#

thats not bad tbh

inland oak
#

xD I even commited my database to this repository. I was really lazy this for pet project.

#

well, it has its benefits. it is really easy to migrate and maintain at least.

sullen pebble
#

but what idk is make.bat, config.py, makefile etc

inland oak
#

don't touch make.bat and makefile, they were auto generated by sphinx initialization, they aren't needed.

#

tbh they should be deleted probably, if it will not break anything

sullen pebble
#

hmmmmmmmmmm

inland oak
sullen pebble
#

whats 'jekyll' again

sullen pebble
inland oak
#

this is main file for sphinx settings

#

you can choose Theme styling and e.t.c. there

inland oak
#

some sort of alternative to sphinx it is

#

probably another way to format documentation easily

inland oak
sullen pebble
#

hmmmmmmmmm

#

can i use the sphinx commands on replit

inland oak
#

replit is highly likely aren't having them

sullen pebble
#

packages?

inland oak
sullen pebble
#

oh yeah repl has them

covert agate
#

what is the best wed-site development maker?

native tide
#

huh

lethal void
#

Hi, I get this error, what do you think seems to be solution.

#

any Django experts ?

nova tapir
#

@lethal void did you just test a forum you filled out that could have an attachment (cv, resume), but you didn't attach a file, and the code assumes you have

wooden ruin
lethal void
nova tapir
#

Good to hear

inland oak
modest ermine
#

Hi All, a beginner's question from my end. In web development, why would you choose JS over Python for backend, or vice versa?

sullen pebble
inland oak
#

That's my hosted made with Sphinx

#

the one to which i gave source code

#

search bar is there

#

there are different themes to choose, I liked this one

sullen pebble
#

idk how to use sphinx :/
and ill have to learn it

inland oak
#

it is quite simple to learn

sullen pebble
#

whats the diff between mkdocs and sphinx?

#

which ones better, which one should i use

inland oak
#

I have no idea what mkdocs is

sullen pebble
#

oh

#

its just like sphinx

#

used to create doc sites

#

all i want to do is

#

create something that can easily display my markdown files

#

so that its easy for the user to view them

sullen pebble
#

looks like i should just create a gist lemon_angrysad

sacred crane
#
response = {}
@app.route('/predict', methods=["POST", "GET"])
def predict():
    if request.method=='POST':
        solute = request.form["solute"]
        solvent = request.form["solvent"]
    else:
        solute = request.args.get("solute")
        solvent = request.args.get("solvent")
    results = predictions(solute, solvent)
    print(results)
    print(type(results.item()))
    response["predictions"] = results.item()
    return flask.jsonify({'result': response})
``` I have build a rest api using flask. when i give `/predict?solute=${form.one}&solvent=${form.two}`; then i get output. but rather than changing the query in url i just want to change url like `/predict` and want to get the output. Because i want to access this in a react frontend
thick sinew
#

Hey guys, does anyone here knows how to make swagger generate documentation for APIView in DRF? It generates docs for generics like ListAPIView but for APIView I need to write schema manually, what does generics have that base view doesn't and makes swagger/redoc/coreapi work? I just get empty method without parameters

serene prawn
#

@thick sinew You need to manually specify request body and responses using swagger_auto_schema in case of drf_yasg

class SomethingAPIView(APIView):
    @swagger_auto_schema(
        request_body=serializer.SomethingCreateSerializer(),
        responses={
            status.HTTP_201_CREATED: seralizers.SomethingSerializer(),
        }
    )
    def post(self, request):
        serializer_in = serializers.SomethingCreateSerializer(data=request.data)
        serializer_in.is_valid(raise_exception=True)
        data = serializer_in.validated_data
        ...
round cedar
#

Anyone can help me with android devp? Trying to bring data from firebase and put in recycle view in app and having a problem there

blazing imp
#

Help, i'm trying to do a folder with the environment files of my project, but the proyet don't read the files. Im using django-environ 0.4.5
error:
django.core.exceptions.ImproperlyConfigured: Set the PROGRES_DB enviroment variable
my code:

ROOT_DIR = environ.Path(__file__) - 3

env = environ.Env()
environ.Env.read_env(os.path.join(ROOT_DIR, ".envs/.local/.postgres", ".envs/.local/.django"))

.postgres file:
POSTGRES_HOST=postgres
POSTGRES_PORT=5432
POSTGRES_DB=cride
POSTGRES_USER=postgres
POSTGRES_PASSWORD=my_password

#

i'm trying to import the 2 envs files, .postgres and .django, but i don't know how

past lion
#

Hello guys

#

I need your help in Django

#

How to make like api endpoint that returns json of all users from database?

sacred crane
#
{"result":{"predictions":-3.5411367416381836}}
```How can i access the floating value using javascript
past lion
#

Hello guys

#

I need your help in Django

#

I had to make like api endpoint that returns everything from the database in json format

#

I wrote code like this and it kinda workedpy def identity_json(request, *args, **kwargs): data = list(identity.objects.values()) return JsonResponse(data, safe=False)

#

It looks like this

#

but i also have many to many field that doesn't show up there in json

lofty copper
#

Is python a reasonable tool and what in that case what packages? Goal: generate a one-page html with headings, some paragraphs of text and some images.

native tide
#

you probably have a while true of a for loop continuosly running

#

i dont understnad what you are trying to do

#

so you send a request and it sends json format back?

past lion
native tide
past lion
native tide
#

so whats wrong w it

#

?

#

If you need a database/business logic/etc then python and django is a good choice

past lion
native tide
#

so

#

remove the if name == "main":

#

and just do it app.run

#

app.run(debug=True)```
native tide
#

i got a question

#

:0

#

{% extends 'main/base.html' %}

{% block body %}
{%for car in all %}

    <div class = "container">
        <div class = "table">
            <div class="row">
                <div class="col-md-3">
                    {{car}}
                </div>
            </div>
        </div>
    </div>

{% endfor %}
{%endblock %}```

```{'BMW M3 E30': {'price': '$', 'description': '', 'seats': '', 'url': ''}, 'Dodge Charger': {'price': '$', 'description': '', 'seats': '', 'url': ''}, 'Polestar 1': {'price': '$', 'description': '', 'seats': '', 'url': ''}}```
#

cant find the bloody

#

price

#

i guess its javascript

#

💀

lofty copper
native tide
native tide
native tide
#

it's python

#

well yes

#

but im making a for loop

#

Did you look at the docs for selected_related

lofty copper
#

Also Im no interested in running python on the webserver, I just want a plain html generated and host that

native tide
lofty copper
#

ok thanks

native tide
#

{'BMW M3 E30': {'price': '$', 'description': '', 'seats': '', 'url': ''}, 'Dodge Charger': {'price': '$', 'description': '', 'seats': '', 'url': ''}, 'Polestar 1': {'price': '$', 'description': '', 'seats': '', 'url': ''}}```

i just dont understand how to read inside the BMW M3 E30 area
#

if you want to show price, I showed you how

#

no u didnt

#

there ya go

#

bossman

#

try {{car["price"]}}

#

tried it

#

same thing

#

[""] doesnt work in html

#

lmfao

#

well I use actual objects instead of dictionaries so I don't have this problem. good luck

white pier
# native tide

maybe try {% for car in all.values() %}
and then past with {{car["price"]}}

umbral rock
#

Hi all, having some trouble with using whitenoise to locally serve my static files for my django website. As soon as I turn Debug to False, I can no longer access my static files. I've installed whitenoise and i've added it to the MIDDLEWARE list in settings.py, but it's still not working. Am I missing something?

#

The static files load fine whenever I have debugging set to True, so I think my STATIC_URL and STATIC_ROOT etc are all okay. This is my first time setting up a django website though so could be wrong.

ocean slate
#

How to install flask in pycharm

snow sierra
#

!code

snow sierra
#

how do i get a clock to frontend, updating on every page reload???

prod_add_date = forms.DateField(label='Date', initial=datetime.now().strftime("%d/%m/%Y - %I:%M"), disabled=True,
        widget = forms.DateInput(attrs={'class':'form-control'})
    )
dense slate
#

How do you handle uploading files to your backend but saving them in the front-end project folder? I'm getting a Detected path traversal attempt error.

#

Basically anything I try to upload outside of the BE project folder gives me this error. I assume that's to prevent uploading files that are like "../../../whatever.jpg" but then how do I actually get it there?

snow sierra
native tide
#

ok

#

and the task u want?

snow sierra
#

after page reaload, catch current time

native tide
#

that will update automatically?

snow sierra
#

exactly

native tide
#

Javascript is able to give u the current time

snow sierra
#

but i think to make this from jinja..

#

yes or js

native tide
#
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();```
Pulled from CodeGrepper
#

then just set the time variable into the element that is displaying the current time

lone hedge
#

hey everyone, looking for some assistance with my flask app and background celery tasks, tasks are executing but not going to queues i believe to be defining in the celery app conf

#

https://github.com/apsamuel/workshop-ctrl-system/blob/main/pylibs/sidecars/metrics/app.py

I'm defining scheduled tasks like this:

metrics_exchange = Exchange('metrics_exchange', type='direct')
celery.conf.task_queues = (
    Queue(name='vmem', routing_key='vmem'),
    Queue(name='swap',  routing_key='swap'),
    Queue(name='cputime',  routing_key='cputime'),
    Queue(name='metrics',  routing_key='metrics.*'),
)
celery.conf.default_queue = 'metrics'
celery.conf.task_default_queue = 'metrics'
#celery.conf.task_default_exchange = 'metrics_exchange'
celery.conf.task_default_routing_key = 'metrics'

celery.conf.beat_schedule = {
    'publish-vmem-60s': {
        'task': 'pylibs.sidecars.metrics.app.publish_vmem',
        'schedule': 60.0,
        'options': {
            'queue': 'vmem',
            'routing_key': 'vmem',
            #'exchange': 'metrics_exchange',            
        },
    },
    'publish-swap-60s': {
        'task': 'pylibs.sidecars.metrics.app.publish_swap',
        'schedule': 60.0,
        'options': {
            'queue': 'swap',
            'routing_key': 'swap',
            # 'exchange': 'metrics_exchange',            
        },
    },
    'publish-cputime-60s': {
        'task': 'pylibs.sidecars.metrics.app.publish_cputime',
        'schedule': 60.0,
        'options': {
            'queue': 'metrics',
            'routing_key': 'metrics.cputime',
               
        },
    },
}

however those tasks are being sent to an auto-generated queue

[2021-11-12 19:09:43,990: INFO/MainProcess] Task pylibs.sidecars.metrics.app.publish_cpustats[969172b3-f99d-4512-8005-4aed0e49ef0a] received
[2021-11-12 19:09:43,992: DEBUG/MainProcess] TaskPool: Apply <function fast_trace_task at 0xb5542030> (args:('pylibs.sidecars.metrics.app.publish_cpustats', '969172b3-f99d-4512-8005-4aed0e49ef0a', {'lang': 'py', 'task': 'pylibs.sidecars.metrics.app.publish_cpustats', 'id': '969172b3-f99d-4512-8005-4aed0e49ef0a', 'shadow': None, 'eta': None, 'expires': None, 'group': None, 'group_index': None, 'retries': 0, 'timelimit': [None, None], 'root_id': '969172b3-f99d-4512-8005-4aed0e49ef0a', 'parent_id': None, 'argsrepr': '()', 'kwargsrepr': '{}', 'origin': 'gen18174@raspberrypi', 'ignore_result': False, 'reply_to': '870d7a81-21e5-3e32-a7db-fe8c3cb61c33', 'correlation_id': '969172b3-f99d-4512-8005-4aed0e49ef0a', 'hostname': 'celery@raspberrypi', 'delivery_info': {'exchange': '', 'routing_key': 'metrics', 'priority': None, 'redelivered': False}, 'args': [], 'kwargs': {}}, '[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]', 'application/json', 'utf-8') kwargs:{})

which i'm not controlling the name of

pi@raspberrypi:~/restart/headunit $ ./dev/rabbitmqadmin list queues
+-----------------------------------------------+----------+
|                     name                      | messages |
+-----------------------------------------------+----------+
...
| 870d7a81-21e5-3e32-a7db-fe8c3cb61c33          | 108   
..
GitHub

Contribute to apsamuel/workshop-ctrl-system development by creating an account on GitHub.

strange shadow
#

hello, im trying to make a website like https://nedbot.org/ but i dont know where to start.

frank shoal
#

you'll want to start by picking a stack.

#

pick a backend, a frontend, and if needed, a database, event broker, worker, etc

#

you should pick one with a nice acronym.

#

for example. MEAN:
MongoDB
Express.js
AngularJS
Node.js

sleek hare
#

What’s a good stack to use Django with? Is there a preference front end to connect to Django? Or not really?

tawny pollen
#
function submitFormData() {
        console.log('Payment button clicked')

        var userFormData = {
        'name':null,
        'email':null,
        'total':total,
        }

        var shippingInfo = {
        'address':null,
        'city':null,
        'state':null,
        'zipcode':null,
        }

        if(shipping!='False') {
            shippingInfo.address = form.address.value
            shippingInfo.city = form.city.value
            shippingInfo.state = form.state.value
            shippingInfo.zipcode = form.zipcode.value
        }

         if(user=='AnonymousUser') {
            userFormData.name = form.name.value
            userFormData.email = form.email.value

        }

        var url = '/process_order/'
        fetch(url, {
            method:'POST',
            headers:{
                'Content-type':'application/json',
                'X-CSRFToken':csrftoken,
            },
            body:JSON.stringify({'form':userFormData, 'shipping':shippingInfo})
            })
            .then((response)=>response.json())
            .then((data) => {
            console.log('Success:', data);
            alert('Transaction Completed');
            window.location.href = "{% url 'store' %}"
            })
    }
#

why are the properties in userFormData and shippingInfo in single quote? are those JS objects or JSON? thanks

umbral rock
#

Hi all, I posted asking for some help with using whitenoise in a Django project yesterday. Any help would be appreciated: #web-development message

lone hedge
lone hedge
#

which fundamentally get serialized to JSON on this line

body:JSON.stringify({'form':userFormData, 'shipping':shippingInfo})
eternal blade
#

Hello, in the django ORM is there a possibility to add a auto incrementing IntegerField and it increments by one per ForeignKey of another model,
for an example ```py
class Channel(Model):
""""A channel of a ChatGroup"""
chat_group = models.ForeignKey(ChatGroup, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
description = models.TextField(max_length=255, null=True, blank=True)
position = models.IntegerField()
created_at = models.DateTimeField(auto_now_add=True)

@property
def group_name(self):
    return f"ChatChannel-{self.id}"

class Meta:
    constraints = [
        models.UniqueConstraint(
            fields=("chat_group", "position"),
            name="Unique channel position"
        )
    ]``` the `position` field will increment by one per `ForeignKey` to the `ChatGroup` model, Thanks 😃
lone hedge
#

will try again later, celery gave me a splitting headache

slim skiff
eternal blade
#

How can I do that?

umbral rock
#

Within Django, If I create a templates folder within an app, do I not need to update my settings.py TEMPLATES DIRS? Or do you only need to do that if you're using a templates folder outside of your app?

Fairly certain my setup is working correctly but I don't want to run into issues further down the road when I add more apps.

frank shoal
sharp jungle
#

I made a path that takes post requests, but how can i access the binary file if I want images to be sent through it?

sharp jungle
#

I think I got it, except how can I save it to a folder?

@app.route("/add", methods=["POST"])
def add(): 
    file = request.files['file']
    if file:
            filename = secure_filename(file.filename)
            # Save to directory
native tide
#

how do i get a sll

#

?

#

wait no

#

i mean how do i get the webroot of my site

inland oak
#

fascinating. reading one book and discovered alternative way to get location of the user.
Apperently all web devices are having automatically available API... for location of the user

Making the right call, it automatically makes browser/device asking for permission to use the user location

which in turns gets precise location shown based on user IP / GPS / wifi / triangulation to cell towers

#
<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <title>Where am I?</title>
    <script src="myLoc.js"></script>
</head>
<body>
    <div id="location">
        Your location will be here!
    </div>
</body>
</html>
console.log("launching js boot!");

window.onload=getMyLocation;

function getMyLocation() {
    console.log("launching geol on boot");
    if (navigator.geolocation){
        console.log("acquiring geolocation");
        navigator.geolocation.getCurrentPosition(displayLocation);
    } else {
        alert("ops, no geolocation support");
        console.log("alert, no geol");
    }
    console.log("finished getmylocation");
}

function displayLocation(position) {

    console.log("starting display function");
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
    var div = document.getElementById("location");
    div.innerHTML = "You are at latitude:" + latitude + ", longitude:" + longitude;
}
#

That's all that it takes

#

result:

accuracy: 3713.4307272065403
altitude: null
altitudeAccuracy: null
heading: null
latitude: 51.539466
timestamp: 1636814290068
#

all is left having a database of country/towns coordinates, to match those Earth coordinates in order to get country/town of the user.

#

Although, asking for user ip address requires no user permission 🤔 So it has its own advantage in comparison to geolocation API

#

but surely geolocation API should be bringing more precise results ;b

#

not really remembering seeing it actively asking permission at any PC web site though, probably it is more used only for mobile apps, i wonder if they request it in the same way or differently

shadow vine
sleek hare
inland oak
native tide
#

Hello, I am working on a Session Security Project along with a company.

We're trying to show the impact of not sanitizing user input (Blind XSS > gets rendered on the admin dashboard via the DB > Cookie Stealing depending on the Cookie flags set.)

This works because there is an admin authenticated when the attacker sends the payload however if there is no administrator authenticated this won't work as there's no cookie to grab so is there any way in PHP to predefine variables so when they send that payload there is already a cookie or for a bot to login to the administrator session and stay authenticated?

Thanks. 🙂

native tide
#

I can make a bot in Python to do this but I want a second option and more better option.

native tide
native tide
#

I am making a WYSIWYG editor using the contenteditable attribute in divs

#

I have implemented font changing

#

I would like to know what font is the cursor on

lone hedge
#

anyone can help with celery issues sending to queues and not the default autogenerated queue please?

last lily
#

Hey, I have a simple fast api thingy that works on my local machine, but when I try to use it on a VPS it doesn't work, I mean the code runs I just don't manage to connect to it. I launch it using 'uvicorn api:app --host 0.0.0.0 8001' Do I need to change the host to the VPS public IP?

lone hedge
vivid canopy
#

who can help me with allauth django?

noble smelt
#
raise exc.NoReferencedColumnError(
sqlalchemy.exc.NoReferencedColumnError: Could not initialize target column for ForeignKey 'Products.product_id' on table 'order_product': table 'Products' has no column named 'product_id'
#
order_product = db.Table('order_product',
    db.Column('order_id', db.String(length=36), db.ForeignKey('Orders.order_id')),
    db.Column('product_id', db.String(length=36), db.ForeignKey('Products.product_id'))
)

class Order(db.Model):
    __tablename__ = 'Orders'
    order_id = db.Column('id', db.String(length=36), default=lambda: str(uuid.uuid4()), primary_key=True)
    total_price = db.Column(db.Integer(), default=1)
    order_date = db.Column(db.DateTime(timezone=True), default=datetime.datetime.utcnow)
    shipping_address = db.Column(db.String(length=255), nullable=False)
    delivered = db.Column(db.Boolean(), default=True)
    
    user_id = db.Column(db.String(length=36), db.ForeignKey('Users.user_id'))
    products = db.relationship('Product', secondary=order_product, backref=db.backref('orders', lazy='dynamic')) 
    
    def get_id(self):
        return self.order_id

    def __repr__(self):
        return f"Order('{self.order_id}, {self.total_price}, {self.order_date}')"
#
class Product(db.Model):
    __tablename__ = 'Products'
    product_id = db.Column('id', db.String(length=36), default=lambda: str(uuid.uuid4()), primary_key=True)
    product_name = db.Column(db.String(length=255), nullable=False)
    category = db.Column(db.String(length=255), nullable=False)
    color = db.Column(db.String(length=255), nullable=False)
    price = db.Column(db.Integer() , default=1)
    quantity = db.Column(db.Integer(), default=1)
    status = db.Column(db.Boolean(), default=True)
    discount = db.Column(db.Integer(), default=0)
    image = db.Column(db.LargeBinary())
    
    store_id = db.Column(db.String(length=36), db.ForeignKey('Stores.store_id'))

    def get_id(self):
        return self.product_id

    def __repr__(self):
        return f"Product('{self.product_id}, {self.product_name}, {self.category}, {self.color}, {self.price}, {self.discount}')"
       ```
golden bone
wind lotus
#

any resources for learning html/css? im fine with reading books or watching YT vids

inland oak
wicked yew
# wind lotus any resources for learning html/css? im fine with reading books or watching YT v...

I really like w3schools.com for reference. You won’t get the whole picture, but it’s more than enough to just start doing, and you can take any html you write in a plain text file and open it with your browser to see what’s there. VSCode also has a Live Server extension that’s really helpful.

https://www.w3schools.com/w3css/defaulT.asp
They also have a CSS… suite? Called W3.CSS which makes it very easy to create a sleek web page. Also look at https://www.w3schools.com/html/html_responsive.asp

coral wagon
#

It's been 4 hours I stuck on geoserver sld issue if anybody help i will save my sss for tomorrow presentaion

#
<StyledLayerDescriptor xmlns="http://www.opengis.net/sld" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.1.0" xsi:schemaLocation="http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/StyledLayerDescriptor.xsd" xmlns:ogc="http://www.opengis.net/ogc" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:se="http://www.opengis.net/se">
  <NamedLayer>
    <se:Name>DBT_MASTER_LIST</se:Name>
    <UserStyle>
      <se:Name>DBT_MASTER_LIST</se:Name>
      <se:FeatureTypeStyle>
        <se:Rule>
          <se:Name>Apiculture</se:Name>
          <se:Description>
            <se:Title>Apiculture</se:Title>
          </se:Description>
          <ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">
            <ogc:PropertyIsEqualTo>
              <ogc:PropertyName>activity_group_name</ogc:PropertyName>
              <ogc:Literal>Apiculture</ogc:Literal>
            </ogc:PropertyIsEqualTo>
          </ogc:Filter>
          <se:PointSymbolizer>
            <se:Graphic>
              <se:Mark>
                <se:WellKnownName>ttf://ESRI Business#U+0042</se:WellKnownName>
                <se:Fill>
                  <se:SvgParameter name="fill">#000000</se:SvgParameter>
                </se:Fill>
              </se:Mark>
              <se:Size>25</se:Size>
              <se:Displacement>
                <se:DisplacementX>0</se:DisplacementX>
                <se:DisplacementY>-1</se:DisplacementY>
              </se:Displacement>
            </se:Graphic>
          </se:PointSymbolizer>
        </se:Rule>
        
      </se:FeatureTypeStyle>
    </UserStyle>
  </NamedLayer>
</StyledLayerDescriptor>```
#

on my local system its working fine, but on remote server it showing

#

Failed to build legend preview. Check to see if the style is valid.

#

when i validated its showing no error

fast briar
#

Can anyone point me in the right direction to figure out how to populate a SelectField in FlaskForm from a database query? I am trying to make selections available to a user depending on the results of a db query. For example, if a user is a member of the "admin" group, the SelectField should show all options from 1 query, but if they are a member of the "regularuser" group, they should get a completely different set of options in the SelectField.

#

Using sqlalchemy with mariadb btw

sacred crane
#

https://www.npmjs.com/package/jsme-react this package is working perfectly fine in reactjs . But not working in nextjs project. can anyone one tell me the reason

sacred crane
coral wagon
hard lagoon
spiral blaze
#

when im doing flask in vscode, why doesnt suggestions popup for flask?

frank shoal
#

You mean type hints?

#

Probably because request isn't properly annotated as flask.Request. it's just a proxy object.

old prawn
#

Anyone got any experience with sqlalchemy ?

spiral blaze
#

@frank shoal are you familiar with jinja syntax?

frank shoal
#

Yes

spiral blaze
#

is there a way to make something that after you logged in , it says your name instead of saying login?

#

i think theres an if statement in jinja syntax

frank shoal
#

{% if xxx %}

#

Then {% endif %}

old prawn
spiral blaze
#

what are you working on lol

#

im working on a simple wikipedia type page

old prawn
#

i pass the name via python return render_template("index.html",name=current_user.name ,tasks=tasks)

old prawn
old prawn
frank shoal
#

I believe current_user is a global variable in jinja

old prawn
frank shoal
#

ah.

old prawn
#

but substitute it for whatever framework you use

frank shoal
#

then you can assign it as one.

spiral blaze
#

my coding experience is so low kinda sad to see

inland oak
# hard lagoon Any help from here would be highly appreciated, https://stackoverflow.com/questi...

The wish to have cache invalidated for one route, after having request to another route, makes it a bit difficult pithink
Essentially caching exists at levels: Framework level (redis) / Web server server side (nginx) / Client side (nginx) / Client side configurable (service workers)
Considering that you need programmable invalidation, web server server side should not work, because I don't know ways to invalidate their cache in a way that suits your case, client side caching...same problem with cache validation, I think will not work too. and I don't know enough about service workers yet.
Framework level (redis or any other alternative) should be definitely working for your case, simple algorithm

Backend:

GET request:
if cache exists, get it (for example from redis)
Otherwise make your SQL request and set cache to redis

POST request:
Delete cache (from redis)
Perform stuff

Well, actually I have another idea. U could be definitely having cache invlidation at client side level too with localstorages. example:

frontend client side

if cache in windows.localstorage exists
get cache from it, otherwise make GET request.

if u make POST request, delete cache from localstorage
then perform your POST request
frank shoal
#

if you just use flask-session, request.session.user.name

old prawn
frank shoal
#

maybe

old prawn
#

hmmm, something to think about.

frank shoal
#

flask session assigns a cookie containing a session id pointing to a local file (or database record)

old prawn
#

btw do you know much about sql-alchemy? struggling with writing a query atm

frank shoal
#

Sure, what code do you have right now?

old prawn
#

class database(db.Model): id = db.Column(db.Integer, primary_key=True) user = db.Column(db.String(200), nullable=False) startdate = db.Column(db.String(10), nullable=False) enddate = db.Column(db.String(10), nullable=False) duration = db.Column(db.Integer, nullable=False)
My Db structure
How would i write a query to only get the results when user="ben"
I use this to get all data but i want to filter to just "ben"
tasks = database.query.order_by(database.startdate).all()

frank shoal
#

.filter_by(user="ben")

#

or .filter(database.user=="ben")

#

the Column type implements all the operators for ease of use in filter statements

old prawn
#

so : tasks = database.query..filter(database.user=="ben") ?

frank shoal
#

i.e. you could do database.user in yourlist

#

I think at least

old prawn
#

hmm i get this " 'BaseQuery' object is not callable"

frank shoal
#

maybe db.query(database).filter(...)

#

you can use multiple models to resolve relationships.

#

.join() will also work

old prawn
#

Ah wait

#

my bad

#

Working!

#

forgot the .all()

#

btw, @frank shoal Would love to see the wikipedia project your working on, Maybe DM me sometime, Happy to show what I'm working on also

frank shoal
#

wiki?

#

I never mentioned any wikipedia project

old prawn
#

my bad haha got confused with the other user

hard lagoon
inland oak
#

where is located the mechanism that updates players every 30 seconds?

hard lagoon
inland oak
# hard lagoon no problem, I think I can figure out the javascript part...

requirements.txt
create venv / pip install -r requirements.txt

redis==3.5.3

if u wish easily raised redis, instal docker-compose and run docker compose up -d in folder with file docker-compose.yml with content below

version: '3'

services: 
    redis:
        image: "redis:alpine"
        command: redis-server --requirepass your_password
        ports:
        - "6379:6379"
        # volumes:
        # - ./redis-data:/var/lib/redis # uncomment for redis perssistance
        # - ./redis.conf:/usr/local/etc/redis/redis.conf # if u wish your own config set
        restart: always

app.py

import redis

REDIS_PASS = "your_password"
REDIS_HOST = "localhost"

redis_conn = redis.Redis(host=REDIS_HOST, password=REDIS_PASS, port=6379, db=0)

redis_conn.set("key", "abc")

print(redis_conn.get("key"))

P.S. redis also gives a thing for pipeline transfer of a lot of values in one request. If needed to speed up transfer of a lot of values sent in one run.

hard lagoon
# inland oak where is located the mechanism that updates players every 30 seconds?

In some file:

/**
 * Periodically update the `model` table, over an interval `ms`,
 * with the data generated from `factory`, and call the `callback`
 * after iteratively updating the whole table.
 *
 * @param {number} ms
 * @param {promise} factory
 * @param {Model} model
 * @param {function} callback
 * @param {string[]} attributes An array of strings to pass as `options.attribute` to `model.findAll(options)`
 * @returns Interval from `setInterval`
 */
function periodicUpdate (ms, factory, model, callback, attributes) {
  return setInterval(() => {
    model.findAll({ attributes: ['id', ...attributes] })
      .then((instances) => {
        factory(instances)
          .then((data) => {
            Promise.allSettled(instances.map((instance, index) => {
              return new Promise((resolve, reject) => {
                instance
                  .update(data[index])
                  .then(resolve, reject)
              })
            }))
              .then((results) => {
                const [updatedInstances, failedReasons] = results.reduce((previous, current) => {
                  if (current.status === 'fulfilled') {
                    return [previous[0].concat(current.value), previous[1]]
                  }
                  return [previous[0], previous[1].concat(current.reason)]
                }, [[], []])
                if (failedReasons.length > 0) {
                  console.log('Unable to update certain instances:', failedReasons)
                }
                callback(updatedInstances)
              })
          })
          .catch(error => console.log(`Unable to get data from ${factory.name}:`, error))
      })
      .catch(error => console.log(`Unable to fetch ${attributes} from DB:`, error))
  }, ms)
}
module.exports = { periodicUpdate }
#

and then in the main entrypoint file:

// UPDATE_MARKET_INTERVAL = 30 * 1000
// stocksDataFactory ->  generates new data, when called
periodicUpdate(
  UPDATE_MARKET_INTERVAL, stocksDataFactory, sequelize.models.Stock,
  (instances) => {
    const data = instances.map((instance) => instance.toJSON())
    console.log(JSON.stringify(data.map(({ code }) => code)))
    io.emit('market', data)
    console.log(data.length, 'Stocks updated')
  },
  ['name', 'code']
)
inland oak
#

no offence, but I think u should refactor it

hard lagoon
hard lagoon
serene prawn
hard lagoon
serene prawn
#

You totally can use async/await syntax here instead of then and catch 🙂

hard lagoon
hard lagoon
serene prawn
#

Not sure how you can create any try-catch pyramids here 🙃

hard lagoon
serene prawn
#

Why not catch different errors in their respective try-catch blocks?

hard lagoon
serene prawn
#

Just don't do operations that can throw multiple errors in single try-catch block?

#
try:
  42 / 0
  my_list[42]
except IndexError, ZeroDivisionError:
  ...
try:
  42 / 0
except ZeroDivisionError:
  ...

try:
  my_list[42]
except IndexError:
  ...
hard lagoon
#

Yep, tysm !! lemon_happy

native tide
#

I have stored pdfs in my database, does anyone know how I can display just the first page of it as a picture in html

native tide
#

I have a pdf model which has a file field

#

how do i update my github respitory by using cmd?

native tide
#

by that I mean cd into your local where you've made the changes

dense slate
#

If you decide to move a directory where you have been uploading files originally (FileField), is there a way to update just the path of all your images without reuploading then one by one?

elfin marlin
#

Hello im not sure if i should post that here but i decided so since its web-dev maybe you are familiar with requests. So im trying to pass an PHPSESSID cookie in a url with python requests but it doesn't seem to work and i dont know why, i have made this script ```py
cookies = {
'PHPSESSID' : 'myPHPSESSID'
}

def get_data(logger_key):
r = requests.get(url, cookies=cookies)

for cookie in r.cookies:
    print(cookie.name, cookie.value)

soup = BeautifulSoup(r.text, 'html.parser')
return soup```

to output the cookies in use. When i dont use cookies in request.get() the output is something like that, "auth_code NO_AUTH
eid blablabla
PHPSESSID myPHPSESSID

" but when i do use cookies in my request (hoping i pass the PHPSESSID) i get the same result without the PHPSESSID

native tide
#

my form is not being read as a post request even when it is recorded as such

#
<form method='POST' action="" enctype='multipart/form-data'>
                            {% csrf_token %}
                            <div class="form-group m-3">
                              <label>Upload pdf</label>
                              <input name="pdf" type="file" class="form-control-file">
                            </div>
                            <div class="form-group m-3">
                                <label>Description</label>
                                <input name="description" type="text" placeholder="Enter a description" class="form-control">
                              </div>
                              <div class="form-group m-3">
                                <label>Select Folder</label>
                                <select name="folder" class="form-control">
                                    <option value='none'>Select a folder...</option>
                                    {%for folder in folders %}
                                    <option value='{{folder.id}}'>{{folder.name}}</option>

                                    {% endfor %}
                                    </select>>
                              </div>
                              <div class="form-group m-3">
                                <label>Create a new Folder</label>
                                <input name="folder_new" type="text" placeholder="Create a new Folder" class="form-control">
                              </div>

                              <button type='submit' class="btn btn-primary m-3">Submit</button>
                          </form>
#

it's still being read is as a get request even though the form says that it is post

native tide
#

is there any way to get the UID that is registered after google login

sleek hare
#

What IDE do you all like using?

wind lotus
#

hello, i created this but the code was really messy

#

was there any better way than having to write out each letter of "down" individually?

native tide
#

using css you would be able to lose the <strong> tags

split snow
#

hello can someone assist here?

#

Hello guys im developing a flask api and then i encountered a problem with swagger that it raise an error

validation error: {'operation': 10, 'operationTarget': [{'_id': 'e7e66327-3ab7-4213-db2d-57fzc1314dg9', 'attribute': {'birthdate': '1990-06-21', 'gender': 'male', 'phone_number': '1234-5678'}, 'user_name': 'john'}]} is not valid under any of the given schemas

true kernel
#

So, what's the most efficient way in you guys' opinion to traverse through a django codebase?

royal dragon
#

come to discord

sacred crane
#
const [solutestate, setSoluteState] = useState();
const [valueInFirst, setValueInFirst] = useState(false);
<input
  className="mr-2 leading-tight"
  type="checkbox"
  onChange={(event)=>{setValueInFirst(event.target.checked)}}
/>
<form
  noValidate
  onSubmit={handleSubmit(onSubmit)}
  className="space-x-4"
>
  <input
     className="shadow"
     {...register("solute")}
     placeholder="SOLUTE"
     onChange={(e) => valueInFirst && setSoluteState(e.target.value)}
     value={valueInFirst && solutestate}
  />
  <input
     className="shadow"
     {...register("solvent")}
     placeholder="SOLVENT"
     onChange={(e) => !valueInFirst &&setSoluteState(e.target.value)}
     value={!valueInFirst && solutestate}
  />
```I am getting false for another input field and when ever I uncheck, the  state value is swapping and the other is false. I have attached the image for your reference in the question. How should i rectify
strange charm
#

Can some help me with django. Hindi?

#

Please DM me

#

can anyone guide me?

dawn shard
#

So I want to append input(thoughts) in json file, but it appends null to it.

#
thoughts = flask.request.form.get("thoughts")

  filename = 'posts.json'

  entry = thoughts

  # 1. Read file contents
  with open(filename, "r") as file:
    data = json.load(file)
    data.append(entry)

# 3. Write json file
  with open(filename, "w") as file:
    json.dump(data, file)
native tide
#

how do I route back to 8000/ with no extra tags in HTML

minor horizon
#

Hello everyone. I'm not new to python but I'm complete new to Django. We have a SaaS product that collects data from web with python and shows it to the user with insights, dashboards etc.

Currently we're using Angular, Flask and Mongo for this. Is Django a good alternative for Angular + Flask part? Can it be done with it? Do you think it could have benefits?

inland oak
#

the amount of javascript makes no sense to use for this purpose tbh, it is simpler just to use HTML <a href="/"></a>

spiral blaze
#

does anyone know how to make an image animation reset smoothly? my animation starts then ends abruptly and just resets

old prawn
native tide
spiral blaze
#

Nope just a hover over image animation, i have it spin like 180 degrees, then after my mouse is not on it, it just resets abruptly

#

i think its css

dense slate
#

Not entirely sure, but my instinct would be to look into mouseover vs. hoverover

#

maybe nullify the mouseleave event

spiral blaze
#

do you know about flask?

inland oak
fair agate
#

How best can I create a search field in Django that supports searching a field in model and also filtering by a date range? I have implemented the search functionality via DRF but ideally I'd like to create a little UI that does both - how best do I accomplish this?

inland oak
#

the rotation is not in the loop though. if you wished a loop

spiral blaze
#

i pretty new to css so why do we need two? like .box and .box:hover? cant we just cram it into one like

            width: 200px;
            height: 200px;
            background-color: blue;
            transform: rotate(180deg);
        }```
#

?

#

@inland oak

#

i think i had it like that before i changed it to one and so it lost the smoothly returning animation

inland oak
spiral blaze
#

ah i see, what does transition do?

inland oak
#

basically box has hidden child :hover

inland oak
spiral blaze
#

ah i see now, hey atleast you're fater than me at learning lol

inland oak
#

recommending HTML CSS Head First book ;b

#

surely awesome to learn basics

spiral blaze
#

are books generally better than videos for you?

inland oak
#

yeah. I am really fast and vivid reader

#

and I hate videos for learning in general. too unefficient for me. too much water. too difficult navigation, too much waste of time.

#

books can be read fast, going through material you know faster, through difficult material as slow as you need

#

all the material is condensed for usefulness, and if not, you can change the speed easily ;b

#

plus with reading thousands of books, my reading speed is just fast

spiral blaze
#

i think the difference between me and you is that i dont really read books when i was younger (and now), so reading docs just makes me super bored, which kinda sucks cause i know docs/books are way better

mortal parrot
#

i think its a mix of both...they play different roles.

inland oak
#

the only exception when i make to video learning, when it requires learning graphical interface, or disassembling some real life thing. in this case, video is always more useful IMO.
never really needed to learn graphical interface though. But I heard Figma designers are having option to learn it only from videos.

native tide
#

I'm trying to make an assignment organizer web app which allows a user to add classes and see who all is in each class

#

how would I structure my models for this

#
class Classes(models.Model):

    name = models.CharField(max_length=255)
    numberOfStudents = ArrayField(Profile)
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

class Profile(models.Model):
    user=models.ForeignKey(User,null=True)
    numClasses=ArrayField(Classes)
#

this is how I structured my models so far but I think it's incorrect

inland oak
#

one class can have many students

native tide
#

and one student can have many classes

inland oak
#

can one students have a lot of classes? well, he can too.

#

basically, many to many relationship then.

native tide
#

yes, so is it proper to have array of classes, and array of students for profile and classes respectively

inland oak
#
class Class(models.Model):
    name = models.CharField(max_length=255)

class Student(models.Model):
    name = models.CharField(max_length=255)
    
class ClassesAndStudents(models.Model):
    student = models.ForeignKey(Student,null=True)
    Class = models.ForeignKey(Class,null=True)

probably this one then.

native tide
inland oak
#

SELECT class.name FROM ClassesAndStudents
WHERE student == your desired student.

#

not remembering how exactly it looks like in ORM, pseudocode will work yeah?

native tide
#

I see, so we need to pass in classesandstudents context which can be filtered by student being the user who made the request

inland oak
native tide
#

ok

#

wait but when would a classes and students object be created, when a user adds a class?

native tide
#

because there's only one student and one class in that model

inland oak
#

warning: i write in pseudo raw SQL language, because I don't remember ORM very well

#

uh, could be probably finding how it is in ORM

native tide
#

it make sense

#

so when we are trying to display all the classes for a user, we filter by user

#

when we are trying to find all users for a class, we filter by class

inland oak
#

yup 😉

native tide
#

that makes way more sense

#

thank you

#

what happens if a student wants to leave a class? how would we remove it from the database

inland oak
#

results = ClassesAndStudents.objects.all().filter(student__name="Alex")
or ClassesAndStudents.objects.filter(student__name="Alex"), perhaps all() is not necessary.
will return the classes. with some not know how modification, it would return class names immediately.
with python we could request class_names as [result.class.name for result in results]

native tide
#

I mean then we can just take the classes object from that

inland oak
inland oak
# inland oak well. good question.

if to be simple, you just delete record from ClassesAndStudents
if to be more advanced, you have... somewhere record about it.

you could just make state of the link as left

class ClassesAndStudents(models.Model):
    student = models.ForeignKey(Student,null=True)
    Class = models.ForeignKey(Class,null=True)
    state= "student_left at date"

or you could be having separate table for leaving records, which sounds a bit better.

class StudentLeftClassAtDate(models.Model):
    student = models.ForeignKey(Student,null=True)
    Class = models.ForeignKey(Class,null=True)
    date = models for date thing
inland oak
#

to one class a lot of students were connected

native tide
#

oh yeah I know

inland oak
#

if you have Foreign Key relation ship with DELETE on cascade

#

you will delete all links

#

for all students) which attend the same class

native tide
#

yeah

#

oh wait

#

don't we just have to delete the classesandstudents object

#

not the actual class

inland oak
#

yup

#

just classesandstudents obj

native tide
#

can we delete on cascade for the student and the class in the classesandstudents object

#
class ClassesAndStudents(models.Model):
    student = models.ForeignKey(User,null=True, on_delete=models.CASCADE)
    Class = models.ForeignKey(Class,null=True, on_delete=models.CASCADE)

#

like this

inland oak
#

uh. it sounds like a bad thing to do 😉

#

I would advice against doing it

#

why would u wish deleting Class or Student?

native tide
#

so just use no action

inland oak
#

I mean...

#

when you setup it like
class ClassesAndStudents(models.Model):
student = models.ForeignKey(User,null=True, on_delete=models.CASCADE)
Class = models.ForeignKey(Class,null=True, on_delete=models.CASCADE)

#

if you delete ClassesAndStudents, you delete just one ClassesAndStudents obj

native tide
#

yeah

inland oak
#

if you delete related student or class, you delete related ClassesAndStudents objects too

native tide
#

oh so then we need to just do no action

inland oak
#

delete on cascade is perfect default relationship

inland oak
#

BUT!

#

usually people never delete objects from classes or students, objects from table full of... dunno how to say that, first layer unique objects?

#

because they would have lost all the related those records

#

they just turn those Students or Classes with additional attribute as "deleted" state or "deprecated"

#

don't delete them 😉 keep them, in case u need to make analytics from the records of the left students too

native tide
#
class Class(models.Model):
    name = models.CharField(max_length=255)
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class ClassesAndStudents(models.Model):
    student = models.ForeignKey(User,null=True, on_delete=models.DO_NOTHING)
    Class = models.ForeignKey(Class,null=True, on_delete=models.DO_NOTHING)