#web-development

2 messages · Page 69 of 1

native tide
#

is there a way to get what I want to do?

ruby fjord
#

probably not

native tide
ruby fjord
#

those kind of pranks only work if the person doesnt copy the link

native tide
#

file:///C:/Users/Daniel/Documents/HTML/index.html

#

oh

#

thats the link for me

#

how do I get him that?

ruby fjord
#

you have to send him the html page

#

like, you have to host the website somewhere and that costs money

native tide
#

oh

#

bruh

ruby fjord
#

well, theres free hosting services

dapper tusk
#

there are free places to put static html

native tide
#

there are?

#

@dapper tusk where

#

whereeeeee

ruby fjord
#

but for what you're doing it's a waste of time

dapper tusk
ruby fjord
#

but github is easier to use

dapper tusk
ruby fjord
#

not gonna help you with that one (github) because there are lots of resources online to help with it

fleet spindle
#

Okay, not sure this is the right place but I’m handing trouble with selenium. I can’t get the web driver to work. Iv downlaoed it and added the exe to path
this is the error:
Traceback (most recent call last):
File "C:\Users\John\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\common\service.py", line 72, in start
self.process = subprocess.Popen(cmd, env=self.env,
File "C:\Users\John\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 854, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\John\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 1307, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "c:\Users\John\Desktop\west wall sorn\Sorn program.py", line 4, in <module>
browser = webdriver.Edge()
File "C:\Users\John\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\edge\webdriver.py", line 56, in init
self.edge_service.start()
File "C:\Users\John\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\common\service.py", line 81, in start
raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: 'MicrosoftWebDriver.exe' executable needs to be in PATH. Please download from http://go.microsoft.com/fwlink/?LinkId=619687

#

sorry for the huge block

atomic zinc
#

Hello all. Can someone recommended me a book/site/app from where I can study Django.(level is begginer)

native tide
#

django docs are honestly great

#

do you have experience with setting up python / virtual environments?

atomic zinc
#

no

#

I now only the basics of python

twilit zenith
#

yeah follow tutorial on Django's website

#

or watch tutorial series by Cory Schafer(where I learnt basics)

native tide
#

I am good at Django project

#

@native tide

#

If you need my help, please contact me.

native tide
#

@native tide S460 was lookin for help 🙂

nova escarp
#

I tried posting this in one of the help channels but maybe someone here can help

#

I'm making a Django web app for restaurant reservations. I have a reservations home page that has that days list of reservations. How could I make it so the home page clears itself every day at midnight so you don't have to manually delete all of the reservations of that day? Also instead of just fully clearing it I would like to store the data from the reservation model of that day or a brief summary version (i.e just the ammt of people that went that day) somewhere else (I'm planning on making a view for that as well). Is it possible to do this? I've tried searching and I haven't been able find anything that does what i'm looking for.

pulsar rain
#

Automatically doing something at particural time is a great job for Celery periodic tasks or for crontab(easier way)

#

but, shouldn't the reservations home page has reservations filtered by a current day?

nova escarp
#

The plan I have is that it only displays current day reservations, and old ones can be found in a different view

pulsar rain
#

moving data from model to another model isn't a good way, I would go with different views with different querysets etc

nova escarp
#

I want to make a "old reservation" view sorted by date which you can click on to see the stats of that day. The plan originally was to move the data from reservations to old reservations. How can I store the reservations data and have it display on the old reservations view?

pulsar rain
nova escarp
#

Thanks!

#

if it'll be helpful i can send my code. What should I send?

pulsar rain
#

Models/Views

#

but anyway you should firstly follow some good tutorial/video about and how to handle filters in Django

nova escarp
#

models.py ```from django.db import models
from datetime import datetime

from django import forms

Create your models here.

class Reservation(models.Model):

name = models.CharField(max_length=40)
member_id = models.CharField(max_length=10, default="")
guest_num = models.IntegerField()
reserve_time = models.TimeField(default=datetime.now)
notes = models.CharField(max_length=100, blank=True)
date = models.DateTimeField(default=datetime.now, blank=True)

def __str__(self):
    return f"{self.name} at {self.reserve_time.strftime('%I:%M %p')}"
#

views.py ```from django.shortcuts import render
from .models import Reservation
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (
ListView,
CreateView,
UpdateView,
DeleteView
)
from django.urls import reverse

class PostListView(LoginRequiredMixin, ListView):
model = Reservation
template_name = 'reservation/reservation.html'
context_object_name = 'reservations'
ordering = ['reserve_time']

class PostCreateView(LoginRequiredMixin, CreateView):
model = Reservation
fields = ['name', 'member_id', 'guest_num', 'reserve_time', 'notes']

# Check if User is submitting
def form_valid(self, form):
    form.instance.author = self.request.user
    return super().form_valid(form)

# Send user back to home on success
def get_success_url(self):
    return reverse('reservation-home')

class PostUpdateView(LoginRequiredMixin, UpdateView):
model = Reservation
fields = ['name', 'member_id', 'guest_num', 'reserve_time', 'notes']
template_name_suffix = '_update_form'
# Check if User is submitting
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)

# Send user back to home on success
def get_success_url(self):
    return reverse('reservation-home')

class PostDeleteView(LoginRequiredMixin, DeleteView):
model = Reservation
success_url = '/'

pulsar rain
#

the field reserve_time and date look confusing, If both of them relate to date of reservation then having one DateTimeField would be better

nova escarp
#

I put reserve_time there so the user can input the time of the reservation, I don't have them putting in the date manually

pulsar rain
#

so it should be DateTimeField instead of TimeField

#

with get_queryset method you may easily change the default queryset in view, what you want

nova escarp
#

Oh I see. quereyset holds the info of each instance of reservation right?

pulsar rain
#

yeah, the default is Reservation.objects.all()

nova escarp
#

not sure what the proper way to do it, but how would I make the home page display only that days reservations

#

I was going to delete it like i said but it looks like I can just leave it there and grab it when I need it?

wind walrus
#

I have a folder for each user storing things like profile pics and spreadsheets

#

On my accounts page I have a FlaskForm with a FileField() for uploading files

#

I've seen people use app.config["UPLOAD_FOLDER"]=path but since the folder name is different for each user, how can I do this?

warm igloo
#
f.save(os.path.join(
    app.instance_path, 'photos_' + user.coolfoldername, filename
))
wind walrus
#

Thanks!

#

Actually, I need to load multiple files at once, so I'm using wtforms MultipleFileField

#

Do you know how to download with that?

#

When I do

#
for file in form.field.data:
  filename = secure_filename(file.filename)
  file.save(os.path.join(app.instance_path,"path", filename))

I get

filename = secure_filename(file.filename)
AttributeError: 'str' object has no attribute 'filename'
brittle iris
#

hey guys how can i deploy my django web app on a ubuntu server ?

odd oar
#

Don't you just like, run it?

brittle iris
#

i really do wish it was that easy.

warm igloo
#

@wind walrus Odd. I can't find anything about Flask-WTF support WTForms' MultiFileField which makes me think you'll need to look at those docs directly. I think what's happening is WTForms doesn't handle the actual file data. That field.data is just filename from WTForms. However, Flask-WTF does support the actual file data for FileField. But if it doesn't handle MultiFileFiled, that means you get the underlying WTForms version. And their docs say you'll need to iterate over request.FILES[]. So read up on that and you should be good.

odd oar
#

oh actually I think this is more relevant

merry geode
#

I wanted to understand the utility of Django Rest Framework. I have been learning Django to build APIs and my front-end is built using Vue.js (I have only basic javascript and Vue.js knowledge).
I haven't used DRF so far. I find that Django's built-in views, including class based views are able to fulfil what I need to do. So I wanted to understand what utility DRF adds and what I would need to do to convert my Django Views into DRF views.

ashen sparrow
#

As someone who is really bad at designing, what would you suggest me to make my portfolio/personal website like? Should I use (and give credits to) a theme of somekind or make a minimalist/not too fancy showcase website?

dapper tusk
#

I was able to create an ok looking website just by looking up the proper bootstrap classes for the contents of a given section

brittle iris
#

has anyone used django with docker on ubuntu server ?

quick cargo
#

Yes?

terse viper
#

hey guys how can i deploy my django web app on a ubuntu server ?
has anyone used django with docker on ubuntu server ?
Assuming you want pointers on deploying a django app using docker:

  1. make a dockerfile that installs your dependencies and copies the server files in and does runserver
  2. build the dockerfile and push to a container registry somewhere
  3. on the server, log into said container registry, and docker run the image providing it with whatever volume mounts, ports, and envs you need, it'll pull it and run it

alternatively for step 3, use some orchestration tool like docker-compose to make that easier

alternatively for step 2, for more manual deployments without using a registry, git checkout your project on the server itself, and docker build on there instead

bleak bobcat
#

alternatively for step 1, don't use runserver on prod....

terse viper
#

true true, do the gunicorn stuff

gritty matrix
#

i know this is web dev but where can i show of my work

twilit zenith
#

@merry geode you'll need serializers to format data in JSON, there are many other things that DRF provides, i personally use Vue JS so I had to convert everything in JSON, if you're using Vue within your Django templates, I suppose you don't have to convert everything in JSON

#

in my case I'm making single page app using Vue so I have to make sure page doesn't reload most of the time

#

lmk if you need help, I'm using same stuff as you if I'm not mistaken

merry geode
#

Hey @twilit zenith , would love to speak to you sometime if you don't mind a dm or two.
But on topic, I just use Django's JsonResponse with safe=False flag. That works fine for me. How is a serializer different?

#

I convert my responses to Python dictionary before sending it

twilit zenith
#

yeah i think its the same, i actually don't know much difference because i recently started learning DRF, i have been using modules provided by it

native tide
#

In Django I am writing a blog app and I have a DetailView for the article model. Now I want to have comments in that article detail view, so I added a list of the comments with the get_context_data function, passing the result to the context. However I am unsure how to tackle the adding comment form. Is it best to use a mixin class, can I pass it also to the context? What is the best approach? Thanks!

amber parcel
#

@solar crag html and css will pretty much come hand-in-hand

#

javascript will somewhat follow along

#

start with html

#

since thats like the base structure

#

that css and javascript can then act on

solar crag
#

thanks, any good sources to learn? i am using udemy for python atm

amber parcel
#

uhhh

#

actually one sec

#

i think i may have something somewhere

#

also when making you html files

#

you don't have to actually host them online

#

to view the frontend

#

just open the document and it opens in chrome

#

in a preview mode kinda thing

solar crag
#

thanks!!

#

do you by any chance know if having a website costs money?

amber parcel
#

it does

#

most of the time

#

any good one will cost money

#

theres some free services that can kind of host your site

solar crag
#

i only know that sites like godaddy sell domains

amber parcel
#

like heroku and stuff

#

but if its free it's not going to be very good

solar crag
#

i see! am i the only one who can work on the website?

#

like is it somehow password locked?

amber parcel
#

i mean

#

you're the one with the code

#

anyone can steal the frontend of a site

#

but its the backend that actually matters

solar crag
#

its not about stealing, but more about people making changes on my website 😄

amber parcel
#

oh well then no

#

unless someone hacks into it

#

which is unlikely

solar crag
#

like hacking a social media profile and changing the bio

amber parcel
#

i mean

#

well its not going to be completely secure

#

but

#

your actual code

#

should be fine

#

i doubt anyone would want to try get that

solar crag
#

I see, i have to learn some stuff about that

amber parcel
#

security is more for like

#

a website with profiles and stuff

#

and you need to prevent peoples getting into other peoples profiles etc

#

idk i'm not super well informed on security

#

but i wouldn't worry about that for a while

solar crag
#

ty, I will finish learning python first tho:D

#

too much at once x)

rustic pebble
#

Depends, if you are using MySQL you need to make sure you sanitize all input

#

@solar crag

solar crag
#

sry, i have not idea what you mean

wind walrus
#

The templates and {% extends “base.html” %} feature is Flask specific right? It’s not a HTML feature

rustic pebble
#

@wind walrus no, it is Jinja specific

wind walrus
#

In which case, if you were to create a website with purely frontend, how would you do sth like templates?

#

Oh

rustic pebble
#

Frontend of a website is not a website, it is just a part of it. A website needs work both ways to make sure its funtional

wind walrus
#

So if you were to use JavaScript as both frontend and backend for example

#

You could still use the templates?

rustic pebble
#

You wouldn't be using javascript for backend you would be using a NodeJS based framework like Express

#

Jinja is python specific but there are alternatives for javascript

wind walrus
#

Yeah nodejs

rustic pebble
#

I usually use SPA frameworks when I use javascript (or typescript) backend, some of these frameworks are React, Vue and Angular

wind walrus
#

Ah okay

#

Does django use jinja?

rustic pebble
#

These are frontend frameworks though

solar crag
#

thanks

rustic pebble
#

Jinja is modeled after Django's template engine

wind walrus
#

Oh wow okay thank you

bleak bobcat
#

You could also use a static site generator if you don't plan on having a backend but still want some content management tools

rustic pebble
#

Yes

wind walrus
#

Yeah, I only need a simple website for a school project, but wanted sth similar to templates

#

To avoid having to copy paste navigation bar and stuff again and again

#

(I’m a high school student)

dense slate
#

Django running in production seems to utilize 3 works when starting gunicorn. When I run a script to import items on a list into a DB from a python file, and restart gunicorn, it runs it three times (though not always) even though the loop is supposed to pass if it sees an existing value. Is there a way to import values (1000+) into a DB without it happening multiple times?

#

Would it work to "python manage.py runserver" after uploading the script (and then ending it), rather than restarting gunicorn, or is that not safe to do in production?

zealous siren
#

Why run inside Gunicorn instead of standalone?

dense slate
#

The site in general or the script?

zealous siren
#

the script to import

dense slate
#

Yea I don't know. I generally restart gunicorn anytime I make changes.

#

Hmm, ok so you're saying just run the one file.

#

That makes complete sense good sir, I'm going to do it.

#

Do scripts need to be registered with Django?

#
/lib/python3.6/site-packages/django/conf/__init__.py", line 64, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
static night
hollow glacier
#

Would this be the way to get the username on the profile model?

from django.db import models

from django.contrib.auth.models import User

class Profile(models.Model):
    username = models.ForeignKey(User, to_field='username', on_delete=models.CASCADE)
    description = models.CharField(max_length=200)
    avatar = models.ImageField(upload_to='images/avatars/')

    user = models.ForeignKey(User, on_delete=models.CASCADE)
serene hedge
#

Hey, I need some help with Selenium anyone got a minute? If so, please @ me

serene hedge
#

Basically I am trying to get the last message sent by a contact in messenger

#

This is for a personal chat bot I'm building

#

I've tried everything

#

But facebook certainly doesn't make it easy

#

So if you think you can help me, please @ or DM me, any help is appreciated!

#

By the way I don't necessarily need exact code to make this work, just a basic explanation / tips and I'll handle it on my own from there. 🙂

nova storm
#

Any of u can help me plz

glass sandal
#

In Django or Flask?

nova storm
#

In making my First Web page

glass sandal
#

Or selenium?

nova storm
#

Django

glass sandal
#

What is the prob?

nova storm
#

With screen sharing

#

I just want to know the concept

glass sandal
#

About what?

#

I can explain you this way

nova storm
#

For eg. Why we use views?

#

How it's work

glass sandal
#

We use views to do python functions in specific urls

#

And you can return html pages by it

nova storm
#

And how to link a page with other

#

Okay

glass sandal
#

Wdym by linking a page?

nova storm
#

By giving link of 2nd page on 1st page

glass sandal
#

Use an "a" tag

nova storm
#

Okay

#

And then href

glass sandal
#

Like <a href="https://www.google.com "> the link</a>

nova storm
#

Okay thanks

glass sandal
#

np

nova storm
#

Can i again catch u up when needed?

glass sandal
#

Well , I may be busy but maybe yep

nova storm
#

Okay thanks😊

glass sandal
#

np

cunning hull
#

If i have a html file with a bunch of variables in it, how can i have flask read that file and the variables

unreal atlas
#

hej

ruby fjord
#

does anyone else get a blank page when redirecting on any browser other than firefox with django.http.HttpResponseRedirect?

scarlet wind
#

is it okay to show someone my cookiekeader

ruby fjord
#

@scarlet wind never do that

scarlet wind
#

why? D:

ruby fjord
#

actually wait

#

yeah you can do that I think, just not personal phpsession id's

#

depends on what part of the header you're giving out

scarlet wind
#

I am talking about in the network inspection tab, where it says set-cookie

#

under response headers

ruby fjord
#

oh

scarlet wind
#

is that okay?

ruby fjord
#

trying to look for it in my inspect element

scarlet wind
#

I think you have set something to a cookie first

ruby fjord
scarlet wind
#

no, in the network tab; click on the html page under names and then go to headers

ruby fjord
#

I guess it's safe, just don't send the cookie

scarlet wind
#

@ruby fjord the cookie didn't have any personal data inside it

odd oar
#

Isn't that all that cookies are for ?

scarlet wind
ruby fjord
scarlet wind
#

is the set cookie header unique to each individual server or cookie?

#

what if I clear my site data, will it be different?

acoustic oyster
#

Howdy, friends.

Does anyone know of any good, professional ways to manage Django settings for developing with a production server?

I.e I have had my server running in production for some time, but would like to completely rewrite the front end using a new branch on GitHub, but am experiencing numerous errors since it was not set up properly originally to handle both production and development environments.

#

the way I usually do it is have a production sql server and a local, test sql server, but this is not super practical.

native tide
#

I am a senior developer. I am good at django development.

acoustic oyster
#

well hello

#

any advice for my issues?

#

or any references to some sort of resource on this would be nice. I realize Django has this documented, but I would like to know if that method is commonly used and how it is implemented exactly.

radiant garden
#

I mean you can just have two copies of the thing on your server. Two checkouts of the repository, with two different configs, pointing to two different databases. And you serve them on two different domains

#

what helps is to not check in your config file, just check in an "example" configuration file and then customize it for each deployment

acoustic oyster
#

kk, ty.

right now my method is to tie the settings to DEBUG mode to determine if it should run production mode or not.

But using this method, I imagine it could be very dangerous when I commit changes to the production server.

I.e: if I makemigrations, or in this case when I updated the local database, I was required to make a new superuser, which I imagine is not going to go over well when I need to push this develop branch to produciton

brittle iris
#

how can i integrate the usage of scss or sass on my django project

molten quarry
#

@barren salmon base.html holds the constant parts of your webpage (navigation bar, css styles, etc).

When you call extend you're basically copying all the html in base.htl to the generated file.

This means that if you want to update your main navbar, you'll only have to do it in the base.html since all other files extend from it.

faint pulsar
#

whats a good resource to learn the trio? HTML CSS and JS? I need something like automate the boring stuff of python for these three

quasi thorn
#

@faint pulsar Jon Duckett has 2 books

#

js and jquery

#

html and css

#

ive heard they are good

gilded monolith
#

@acoustic oyster maybe i arrive late to the party, but you can specify different configuration files and tell what to use as a environment variable? Of course you would complete prod secrets only on the production machine.

#

Your db for dev and prod should be different imo.

acoustic oyster
#

haha, thank you for your reply. Yeah, I'm trying to get this down. I need to do some reading too.

and yes, I keep them separate, but from what I understand running a "makemigrations" even on the dev server would mess up the migrations folder as a whole? Just a lot of things i'm trying to consider.

gilded monolith
#

So no worries with migrations and users and what not. For testing, i think Django build and delete a MySQL db, applying all the migrations files

acoustic oyster
#

ty, yeah, I nuked my db once on accident and am super careful now

gilded monolith
#

You shouldnt mess your migrations as a whole if you dev on a separate branch

#

You can also unaply migrations

acoustic oyster
#

yeah, ty. I learned that much later.

From what I read it is standard to keep separate config files, at the moment I have it tied to my DEBUG in settings, I realize the issues with this though.

gilded monolith
#

Yeah, config and deployement are the hard part the tutorial skip throughs usually

acoustic oyster
#

It all just seems very fragile to me (perhaps because I do not know enough) as I have had so many issues trying to update the production site

#

yeah, I love corey schafer, but he kinda screwed me in that area

gilded monolith
#

It is a real problem people argue about for years

acoustic oyster
#

Good to know.

I want to make sure what I am doing is at least acceptable since I am mostly on my own with these projects. Feels bad when I am doing something very wrong for so long. I guess that's how I learn though.

#

Also it helps with my dreams of maybe being able to do this professionally lol

#

but thats a big RIP

terse surge
#

Howdy, friends.

Does anyone know of any good, professional ways to manage Django settings for developing with a production server?

I.e I have had my server running in production for some time, but would like to completely rewrite the front end using a new branch on GitHub, but am experiencing numerous errors since it was not set up properly originally to handle both production and development environments.
@acoustic oyster make a folder called settings, inside it make a file called base.py then paste ur settings.py file, now make a dev.py file and a production.py file, then add the dev settings to the dev.py file and do the same for the production.py and do mind that u need to import the base.py file and now in dev.py in databases use sqlite db, rename the db to dev.sqlite and for production if ur using a remote db u dont need to change anything. Now in wsgi.py and manage.py files u will need to set them to projectname.settings.base or production. Hope this works for u. Have a good day

acoustic oyster
#

Ok, I will be rewriting my project over the next few days.

Ty very much for everyone's late night help.

limber laurel
#

Is there something like the debug panel in Django, in flask?

terse surge
#

Ok, I will be rewriting my project over the next few days.

Ty very much for everyone's late night help.
@acoustic oyster ur welcome, also its morning for me rn

acoustic oyster
#

haha, I figured that's why I was getting more responses now.

worn aurora
#

i have made a blog in wagtail (django CMS)
i want to make some dummy pages to display how can i do so
one way is i add pages through admin portal but that is long and tedious
is there any way i can do this programmatically

crude swan
#

anyone around for a django question?

rigid laurel
#

best to just ask

#

you probably won't get an instant response, but if you ask someone will hopefully come along at some point who knows the answer

crude swan
#

okay. I tried supplying a local folder as a download to a user with a simple <a href"pathtofile" download> tag. This worked fine with debug=True but failed when False. I switched to returning a FileResponse and that seemed to work for both, however it requires a page refresh after the download to update page info/styling etc. Is it possible to eliminate the need for a refresh e.g. with ajax? thanks.

rigid laurel
#

what exactly is it that you're trying to do at a high level?

crude swan
#

stop the need for a user to reload the page after downloading a folder

#

i'm using django FileResponse to provide the download,

rigid laurel
#

well, you want to send the file as an attachment?

#

i.e you want them to download a .zip?

crude swan
#

that is already working

#

it's the need for a refresh after

rigid laurel
#

but you want it to work without hte refresh right?

#

refresh*

crude swan
#

yeah

rigid laurel
#

you need to send an as-attachment header somewhere

#

1s

crude swan
#

ahh okay great, i wondered if I could solve it within the response

#

thanks

rigid laurel
#

hm - that doesn't actually look 100% right to me. But if you google around for similar things, it's definitely a solvable problem.

crude swan
#

i'm currently using attachment; filename

#

i'll switch to inline

#

hmm no change

#

i'll look more into it though

rigid laurel
#

I've solved this exact thing before. I'll have a look at how I did it, just need to find the project

crude swan
#

maybe i've explained this wrong because I actually want a page refresh to take place but without the need for the user to do it

#

is that what i've said?

#

like an ajax call but for FileResponse

rigid laurel
#

ah - I might be misunderstanding. What I understand your problem as (possibly incorrectly) is:
You want the user to click a button and download a zip/pdf/img to their downloads folder without refreshing the page.

#

click a button or link or get redirected to it however else

crude swan
#

right. my fault. the download doesn't refresh. i want it to

#

the download works

#

but i would like a refresh straight after

#

but without the user needing to refresh manually

rigid laurel
#

That sounds like it would be easiest solved with JS. Not entirely sure. SEeems like a weird thing to want to be doing

crude swan
#

yeah it's because i'm updating the page state as the user goes through certain tasks

keen lily
#

I keep getting an error

#

when trying to display information from a database onto a page

#

can anyone help

crude swan
#

That sounds like it would be easiest solved with JS. Not entirely sure. SEeems like a weird thing to want to be doing
@rigid laurel thanks for trying Charlie. I'll have a think

real hare
#

I'm looking to compare a user against an authenticated user in my django template. Is it best to do as

{% if request.user == User.username %}

# insert logic here

{%endif%}

bleak bobcat
#

That would be comparing a user to a username

real hare
#

Yup, I wanna compare a user against a username

thorny geyser
#

why would you do it in the template instead of passing a value?

real hare
#

It's so I can filter based off users

#

I'm using a single view for two pages

bleak bobcat
#

Yup, I wanna compare a user against a username
@real hare You can't. You can compare a user to a user, a username to a username, but not a user to a username

real hare
#

@bleak bobcat what's the best way to compare a user in relation to models?

native tide
#

z̯̯͡a̧͎̺l̡͓̫g̹̲o̡̼̘

bleak bobcat
#

Whatever is unique in that model, id for example

lofty matrix
#

In Django, I have a model like this

class Person(models.Model):
    name = models.TextField()
    friends = models.ManyToManyField("self", blank=True, symmetrical=True)

I want a person to be able to be friends with other people, but not with themself. How can I prevent that, ideally in a way that removes the option from django admin?

native tide
marsh canyon
#

you could make a another model just for friends and have a ForeignKey relationship(one to many) with person

worn aurora
#

can i ask ??

#

or still occupied ?

marsh canyon
#

go ahead

scarlet wind
#

I am having trouble with storing dictionaries in flask session. What is weird; is it will save to the browser's cookie. But not quite the python session dict; when I refresh my page or go to a new route the data in the dict is gone, but my cookie is still there. Here is my code:

        if 'Cart' in session:
            session['Cart'][name] = {dict}
            session.modified = True
            print(session)
            print('cart found in python session dict')
        else:
            session['Cart'] = {dict}
            session.modified = True
            print(session)
marsh canyon
#

what does {dict} mean

#

if you want empty dict, then just {}

scarlet wind
#

i put it there because my real code is a long dict

glass sandal
#

Guys what would u do in Django/Flask if you are bored?

#

I have no ideas to make any websites

marsh canyon
#

try open source projects

#

the pydis site is built on django and is open source

worn aurora
#

my ques
i have made a blog in wagtail (django CMS)
i want to make some dummy pages to display how can i do so
one way is i add pages through admin portal but that is long and tedious
is there any way i can do this programmatically

glass sandal
#

wdym by trying open source stuff?

#

Oh you mean making them?

marsh canyon
#

no

glass sandal
#

Then what?

#

Contributing?

marsh canyon
#

contribute to pre-existing django projects

glass sandal
#

Oh

marsh canyon
#

@worn aurora if a blog is a model(which I assume), then just make a function which creates dummy models in a loop, then called that function from a view

worn aurora
#

i have a foreign key in my model how do i handle that ?

#

and can u provide some examples ?

glass sandal
#

Guys is there something like Website jams?

#

Like Game jams , but for websites

marsh canyon
#

@glass sandal the upcoming jam is based on django

glass sandal
#

Oh nice

marsh canyon
glass sandal
#

But what about like another things

#

I mean

#

We don't have site jams always

#

Then is it an alternative?

marsh canyon
#

@worn aurora fetch the foreginkey model instance first and then assign it

glass sandal
#

kk

worn aurora
#

let me try

#

well im trying to do this

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'codingplusplus.settings.dev'
import django
django.setup()

import json 
from faker import Faker
from wagtail.core.models import Page
from blog.models import BlogEntryPage

parent_page = Page.objects.get(title='Coding Posts').specific

faker = Faker()    
entry = BlogEntryPage.objects.get(title="test-01")
for i in range(0,10):
    fake_page = BlogEntryPage(
        created = faker.date_time_this_month(),
        updated = faker.date_time_this_month(),
        search_description='',
        seo_title='foo',
        show_in_menus=False,
        title = str('test-0'+str(i)),
        slug= str('test-0'+str(i))
    )

    fake_page.body.stream_data = entry.body.stream_data
    fake_page.tags = entry.tags
    fake_page.category = entry.category
    fake_page.CoverImage.stream_data = entry.CoverImage.stream_data
    fake_page.ScreenWidthCoverImage = entry.ScreenWidthCoverImage


    parent_page.add_child(instance=fake_page)
    revision = fake_page.save_revision(
        submitted_for_moderation=False,
    )
    revision.publish()
    fake_page.save()
#

but i get error

marsh canyon
#

whats that error?

barren phoenix
#

Does anyone know how i would go about letting a user displaying videos instead of images in Django. If you have any ideas please dm me or just @ me. Thanks in advance!

lavish prismBOT
#

Hey @worn aurora!

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

worn aurora
marsh canyon
#

the error from elsewhere, its saying there is no key called type

#

check your parent_page.add_child method

worn aurora
#

is base.html in same app ?

cold anchor
#

and are you rendering home.html? and does base.html have a block named "content" in it?

native tide
#

any idea why i always get 401 unauthorized when i add @login_required to route?
heres my login function:

@app.route('/api/login', methods=['POST'])
def login():
    req = request.values
    _id = req['id']
    print(_id)
    _password = req['password']
    print(_password)

    if _id not in USERS:
        return {'message': 'Invalid credentials'}, 401
    elif not USERS[_id].can_login(_password):
        return {'message': 'Invalid credentials'}, 401
    else:
        USERS[_id].authenticated = True
        login_user(USERS[_id], remember=True)
        return {'message': 'Logged in'}, 200
#

here's my user model, if needed

class User:
    def __init__(self, _id, _password, _score=0,
                 authenticated=False):
        self._id = _id
        self._password = _password
        self._score = _score
        self.authenticated = authenticated

    def __repr__(self):
        r = {
            'id': self._id,
            'password': self._password,
            'score': self._score,
        }
        return str(r)

    def can_login(self, _password):
        return self._password == _password

    def is_active(self):
        return True

    def get_id(self):
        return self._id

    def is_authenticated(self):
        return self.authenticated

    def is_anonymous(self):
        return False
#
req: print(requests.post(url+"login", data={"id":"test", "password":"1"}).content)
result: b'{\n  "message": "Logged in"\n}\n'

req: print(requests.get(url+"users").content)

result: b'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n<title>401 Unauthorized</title>\n<h1>Unauthorized</h1>\n<p>The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a bad password), or your browser doesn\'t understand how to supply the credentials required.</p>\n'
nova escarp
#

Im using Django and I got a Model called Reservation. I want to have it automatically check what the user inputted into a variable called reserve_time reserve_time = models.TimeField(default=datetime.now) I want it to check if the time inputted was before 4 pm or after 4pm and then depending on what it is change a variable to either lunch or dinner. I tried setting up a decorator and a function that has an if else statement but I couldn't get it to work, any ideas?

marsh canyon
#

You can override the save method to implement your calculations

#

Or can use Django signals too,like post_save

nova escarp
#

I found something about post_save

marsh canyon
#

It's best to have signals in their own separate file

nova escarp
#

Oh ok gotcha

marsh canyon
#

And use a connector

nova escarp
#

just import it into models then?

marsh canyon
#

Yes and then u have to use signal.connect method

nova escarp
#

Thanks!

#

the most trouble i'm having is figuring out what code goes to what file lol

marsh canyon
#

There are pretty good YouTube vids too which cover Django signals incase the docs are confusing

nova escarp
#

This is what i've got so far ```def model_created_or_updated(sender, **kwargs):
the_instance = kwargs['instance']

reservation = Reservation.objects.last()
if reservation.reserve_time < datetime.time(17, 10, 0):
    reservation.shift = 'lunch'
else:
    reservation.shift = 'dinner'

post_save.connect(model_created_or_updated, sender=Reservation)```

#

The issue is Im not sure how to make it grab that specific instance of the class, what I get instead is <django.db.models.query_utils.DeferredAttribute object at 0x7fdae2b7b8b0>

native tide
#

you could optionally make the if-else query at the html with the template language i think...

nova escarp
#

Yeah, but I want to have it attached to the model so I can sort it later

#

also i get this ```descriptor 'time' for 'datetime.datetime' objects doesn't apply to a 'int' object

native tide
nova escarp
#

I figured mine out too... I had a wrong import -_-

native tide
#

:p

rugged thicket
#

Hey, does someone that has developed with django + react.js can tell me how feasible it is vs just using django to render frontend please?

cold anchor
#

generally, if you're using reactjs you probably only want django as an API layer, so you wouldn't be using its templating features very much

#

but it's easy enough to start a create-react-app project in your django project and have the JS/CSS assets compile in a place that django can serve them

rugged thicket
#

Yes, I'm trying to "dockerize" a web app so I would serve the front end with react, and the backend with django. I just wanted to know if it is "industry" approved

cold anchor
#

yes that's industry approved

#

very standard

rugged thicket
#

thanks!

radiant garden
#

You probaly don't want to serve the React frontend with Django though. Put it on a CDN or at least serve it from a web server directly

cold anchor
#

right ☝️ to reiterate, don't combine react with django templating (too much)

covert trench
#

Django models. How to block removing 0 from numbers? If I have 10.00 django removing last 0 and I get 10.0 :(

radiant garden
#

Floats don't have a number of decimal places associated with them. You can change how many places you want when displaying them though

lavish prismBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

radiant garden
#

f"{n:.3f}" -> 10.000

covert trench
#

thanks

native tide
#

hey, im just starting out in react js, im trying to make my portfolio site. im not sure as to why nothing is rendering

#

could anyone help me thanks

#

hey

#

does anyone know how i can post something on a website and show it x amount of time with flask

#

hey

#

b r u h

thorny geyser
#

import datetime, datetime.now ?

#

something like that, i forgot the exact lines

#

it wont be dynamic withflask tho

native tide
#

why not

ruby palm
#

Hello

native tide
#

hi

ruby palm
#

Turns out I made a selenium project for some reasons (I wanted to automate something out of a website) and then some days later after I began programming and testing it, the programmer of THAT website implemented a captcha thing that you need to fill in order to go to the website.

Is it a coincidence? Or did he detected my bot doing stuff?

(my bot didnt make any POSTs, just some GETs and took some screenshots everytime I executed the script with python and I didnt executed it that many times, only six an hour in a day or something like that)

native tide
#

whats the website

ruby palm
native tide
#

captcha lolz

#

i see

quick cargo
#

if they've added a captcha its very apparent that they dont want people scraping and automating that

wind escarp
#

Turns out I made a selenium project for some reasons (I wanted to automate something out of a website) and then some days later after I began programming and testing it, the programmer of THAT website implemented a captcha thing that you need to fill in order to go to the website.

Is it a coincidence? Or did he detected my bot doing stuff?

(my bot didnt make any POSTs, just some GETs and took some screenshots everytime I executed the script with python and I didnt executed it that many times, only six an hour in a day or something like that)
@ruby palm it doesn't seem like a coincidence to me, probably the admin reviewed the logs and learned someone (you) sent a dozen requests within milliseconds

native tide
#

i would just solve the captchas and then send the cookies together with the requests

quick cargo
#

yeah dont do that

#

!rule 5

lavish prismBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious/inappropriate or be for graded coursework/exams.

wind escarp
#

actually, he can't do that, it's not easy to get through their AI

#

for me, it just shows cloudflare not captcha

ruby palm
#

@ruby palm it doesn't seem like a coincidence to me, probably the admin reviewed the logs and learned someone (you) sent a dozen requests within milliseconds
@wind escarp Very interesting! The weird part is that my script made very few GET requests, like a normal user, it might be just a coincidence

#

for me, it just shows cloudflare not captcha
@wind escarp But when five seconds pass I have to fill a captcha to verify I'm not a robot, that's what I meant with captcha

quick cargo
#

you can do alot to detect bot activity on sites

wind escarp
#

^ true, and that's because lots of people use the same tools for scraping

quick cargo
#

defcon has some amazing talks on fighting back against web scrapers and spiders

wind escarp
#

@wind escarp But when five seconds pass I have to fill a captcha to verify I'm not a robot, that's what I meant with captcha
@ruby palm you mean, you as in visiting the website through your browser or doing it with bot?

ruby palm
#

Doing it with the bot

#

But the bot makes some GET requests like a normal user

#

Because all I want it to do is to take some screenshots and quit

wind escarp
#

did you use proxies or your own IP for all connections?

ruby palm
#

My own IP

wind escarp
#

that's the problem then

ruby palm
#

Really? But it's the same as if I was just visiting the website and quitting

wind escarp
#

it's a little illegal

quick cargo
#

we cant really help you fix this btw

#

because the site has made it very apparent it does not want it's site being automated

ruby palm
#

we cant really help you fix this btw
@quick cargo I know I know, I wanna know if is it a coincidence or not

#

because the site has made it very apparent it does not want it's site being automated
@quick cargo Exactly!

wind escarp
#

it's not

ruby palm
#

it's a little illegal
@wind escarp What? How is it illegal to make a bot go to a website's url and take a screenshot and quit?

wind escarp
#

I also don't know, what you do is not illegal but the rules its illegal so its illegal 😛

#

check your inbox

ruby palm
#

But my bot was only executed when I did python main.py, it wasn't scheduled nor it didn't work on a server, it's exactly like if I go to voxed.net go to a post and take a screenshot

#

I don't get why you think it's not a coincidence

#

This is how you may detect a bot, but it's not something you see on the logs, right?

native tide
#

ive just spent the past two hours trying to figure out reactjs on repl.it

#

can someone please explain to me what the difference between react, reactjs and react express is

#

im so goddamn frustrated with wasting my time not knowing why my reactjs isnt working

ruby palm
#

React and ReactJS are the same thing, Express is a nodejs framework, you use it on backend with javascript

native tide
#

so why is none of my react rendering on repl

#

i assumed it was because i used react in reactjs or something

#

but nothing i try works

ruby palm
#

I suggest asking React questions in a frontend development server

#

Let me look for one

#

Sent you the invite link through DM!

quasi thorn
#

what should one learn first js or html and css

terse viper
#

usually you'll want to know just enough HTML to understand how Javascript fits into it

#

and just enough CSS to position and style your stuff

#

once you get enough knowledge of HTML and CSS to know how everything fits together, then learn Javascript

quasi thorn
#

wats diff between normal html and html5

terse viper
#

complex question

quasi thorn
#

like python2 and 3?

somber aurora
#

can I sign up for code jam or do I need to qualify

terse viper
#

html5 is an ambiguous term because of the way people use it

#

the current version of HTML is version 5, and that's the one that we should all be using. It's true that HTML4.01 exists, but it's over 10 years old and nobody should be using it

#

therefore when you say "html" it is probably version 5. HOWEVER

#

these days, "html5" is also used informally to refer to "html + javascript" which is very confusing

quasi thorn
#

is react more powerful than css and html

terse viper
#

it's not one or the other

somber aurora
#

I think so

quasi thorn
#

cause ive heard react and django is a powerful combo

somber aurora
#

yh

terse viper
#

you don't learn either/or. Trying to learn react without first learning html would be weird

quasi thorn
#

ik

#

ok thnx for info

somber aurora
#

I use Html, CSS and django I rlly want to learn react

terse viper
#

though it's true that when you use react, you no longer write raw HTML

quasi thorn
#

lol wats diff between react and reactjs

terse viper
#

as for CSS, again, when you use react, you will be using some kind of CSS parser, which will ultimately generate the CSS. And again, you would no longer be writing raw CSS, but you'd still need to know it

#

react and reactjs are two ways of referring to the same thing

#

although

#

there is also "React Native", but nobody calls this just "react"

quasi thorn
#

thats wat i meant

terse viper
#

you will find a lot of things in javascript have "js" at the end of it which can sometimes be omitted

#

React Native is for mobile apps

somber aurora
#

what's json

quasi thorn
#

its a js data structure

#

format

terse viper
#

JSON is a data interchange format derived largely from javascript's object notation (hence JS O N), it's a format that many language support, including python via the json module

somber aurora
#

ah OK

quasi thorn
#

many things use json

somber aurora
#

thanks

terse viper
#

react + django is quite powerful, but I feel there is too much overlap in responsibilities. I don't like this combination because both react and django deal with MVC

#

which to me is weird and redundant. but I can't argue against it being a powerful combination

#

In my projects, I've gone with Flask or Tornado for the API. This provides most of the features needed, but I'll freely admit that this is missing the automatic admin panels that django provides, and I don't have a good alternative for that. I end up just having to either create those admin panels myself, or not having them

quasi thorn
#

ok thnx

viral sphinx
#

Hey guys I’m trying to run some test cases that require queries. I wanted to know if it was possible to migrate into another separate database (that I’m using for testing)

#

But my initial database is already created

#

How would I make that possible

nova escarp
#

I've got this post_save signal set up that checks if there is a new instance of the model created and it checks if it the time entered is for lunch or dinner and then changes a variable in the class to whatever time of day it is. The issue i'm finding is that it isn't actually changing the variable, its just leaving it as is. I have a print statement so i'm pretty sure it is working when a new instance is created, its just not saving to the class. Heres my code ```def model_created_or_updated(sender, **kwargs):
the_instance = kwargs['instance']
reservation = Reservation.objects.last()

if reservation.reserve_time < datetime.time(17, 10, 0):
    reservation.shift = 'lunch'
else:
    reservation.shift = 'dinner'
    
print('model created/updated')

post_save.connect(model_created_or_updated, sender=Reservation)```

#

how come in the if/else when i change the variable shift is supposed to be it doesn't update into the class's instance? If i do it manually in the python shell it seems to work, but when doing it through this it isn't working.

native tide
#

Is there a big difference between which database server I learn Django with?

terse viper
#

for learning, generally no

#

they all have your basic features that you'd expect for doing database things

acoustic oyster
#

hello friends, If I have:

class Post(model.Models):
  chapter_number = models.IntegerField(default=0)

but I would like the default to be auto filled to be the current number of posts, would it be possible/a bad idea to use something like:

class Post(model.Models):
  chapter_number = len(Post.objects.all())
nova escarp
#

Anyone know if theres a limit to how many instances of a model you can have?

#

or at least how many is reccomended

acoustic oyster
#

also: nvm to my question, I just derped I believe. I can just use the id or an autofield

#

there is no hard limit to number of instances

nova escarp
#

but is it good practice to clear it out every once and a while or does it not matter?

acoustic oyster
#

if you are saving to a database, such as with django models, the limit is your db performance.

I believe python discards objects that are not referenced later in code, but I could be wrong.

#

The limit here I assume would be your ram, and how many instances can physically be handled, but it is likely that whatever you are doing will not need to worry about that.

nova escarp
#

gotcha, thanks!

native tide
acoustic oyster
#

does the serializer field for "detail" match the name of an attribute to a model? Idk, im a noob to django rest

native tide
#

Yea

#

The first listapiview working

native tide
#

does the serializer field for "detail" match the name of an attribute to a model? Idk, im a noob to django rest
@acoustic oyster nvm, idk how the primary key of first object is 6 instead of 1, that was causing the issue

coral marten
#

whats the right practice for putting logic into routes vs templates in flask?

#

I have 3ish if statements and I am unsure whether I should put them into the route or the jinja2 template

radiant garden
#

How do people do live notifications on websites, like google chat? I can use a pub/sub mechanism in the backend, like Redis or RabbitMQ, but does that mean that for every browser connected via websocket to my web server, I open a channel from the web server to the pub/sub server in turn?

#

and subscribe to whatever queue/topic the user should be notified of?

icy wasp
#

can I sign up for code jam or do I need to qualify
@somber aurora do the qualifier and there's a Google forms to sign up

empty anchor
#

Hey so i am trying to setup a automatic job in my django project based on different dates for users. Does anyone know how can i do it ? Ive looked up CronTabs and Schedule documentation but could'nt undersatnd.Can anyone here help me out ?

somber aurora
#

thanks @icy wasp

mellow wadi
#

Could anyone familiar with plotly help me with a current network graph Im building. Im attempting to add a slider that allows the user to view the addition of each edge from a data set, but I'm having trouble getting the slider working as each edge is its own trace (due to having varied colors), and Im not sure how to properly implement it. More details can be provided upon inquiry. Thanks!

thorny geyser
#

Hey so i am trying to setup a automatic job in my django project based on different dates for users. Does anyone know how can i do it ? Ive looked up CronTabs and Schedule documentation but could'nt undersatnd.Can anyone here help me out ?
@empty anchor sure what do you need help with?

#

do you not understand celery itself or the scheduling?

empty anchor
#

do you not understand celery itself or the scheduling?
@thorny geyser no i dont

#

i know what schduling is ,,, but havent done in it django ever

limber laurel
#

Is there a panel like Djangos debug pannel in Flask?

thorny geyser
#

im not familiar with djangos debug panel but usually you just write FLASK_DEBUG = 1

#

in cmd

#

cuz theres no panel

limber laurel
#

Well I mean maybe an external library for flask

naive venture
#

I need some help with django queries.. I have a model with User foreign key and want to filter objects by the user and django keeps telling me Field 'id' expected a number but got 'admin'

native tide
#

I am load a json into html table. All works fine, until I add this json value to the json array.

{
    "name": "embed",
    "desc": "Allows you to send a message embed",
    "usage": "embed <title> <description> <channel>"
},

If i remove this part then it works fine, and if i add it to the bottom of the json it works fine. But if add in middle then it only shows half the json data in the table

#

i find the problem is this: in the usage field if i remove <title> <description> <channel> then it is working but if i add it breaks

barren phoenix
#

Hi i am really new to this and i was just wondering if anyone could check out my question on Stack Overflow?

glass sandal
#

Guys don't u get bored making websites?

wooden badge
#

how do i reference a variable created in python with flask api to a javascript variable in main.js

glass sandal
#

Just do var flask_value = {{ value }};

#

That'd work

#

And I forgot the ;

wooden badge
#

tried it before, will try with different names

glass sandal
#

Didn't it work?

#

You can try to do a script tag before refrencing to your main.js and do var flask_value = {{ value }}; in there?

#

And you have {{value}} defined when returning the page right?

wooden badge
#

to be honest i would try something before figuring that

#

so for example you can print in terminal using console.log(variable) right?

glass sandal
#

Right

wooden badge
#

`var isattractive = {{ plabel }};

function attf(event) {
console.log(plabel)
document.getElementById("attractiveness").innerHTML = isattractive;
}`

glass sandal
#

nonnonono

#

You must console.log(isattractive);

wooden badge
#

correction

glass sandal
#

So I don't see any problems here I guess?

wooden badge
#

i saw it as soon as i posted lol

glass sandal
#

lol

wooden badge
#

the console.log should spit out the string in the running terminal?

glass sandal
#

ummmm?? not in terminal . just press F12 if you are in Chrome then open the Console tab

#

And you'll see values there

wooden badge
#

ooh

glass sandal
#

It shows it in terminal if you run the main.js with Node

#

And that means no flask server

#

So it must return in your browser console

wooden badge
#

Uncaught TypeError: plabel is undefined attf http://127.0.0.1:5000/static/js/main.js:14 onclick http://127.0.0.1:5000/articles:1

glass sandal
#

Did u fix it?

wooden badge
#

So it must return in your browser console
@glass sandal yeah i figured

#

no

glass sandal
#

you must console.log(isattractive)

#

not plabel

wooden badge
#

should i explain more of what im doing?

glass sandal
#

I mean

wooden badge
#

you must console.log(isattractive)
@glass sandal i did so

glass sandal
#

And it didn't work?

#

You can try something

wooden badge
#

i did not lol

glass sandal
#

Goto your HTML file and add a script tag before referencing to your main.js

wooden badge
#

ok

glass sandal
#

And in that script tag

#

define isattractive

wooden badge
#

and insert the function used?

glass sandal
#

to {{plabel}}

wooden badge
#

oh ok

glass sandal
#

and remove the definition in main.js

#

cause you defined it in your HTML

wooden badge
#

`<script type="text/javascript">
var isattractive = {{ plabel }};

function attf() {
console.log(isattractive)
document.getElementById("attractiveness").innerHTML = isattractive;
}
</script>`

#

k let s see

glass sandal
#

No need for function

#

But ok

#

You can define function in main.js

wooden badge
#

ok

glass sandal
#

And did you remove the var isattractive = {{ plabel }}; in main.js?

#

If no , remove it

wooden badge
#

oh ok i ll do that

glass sandal
#

Hmmm

#

None is not defined?

#

Maybe the plabel value is None

#

You can add " before and after the {{ plabel }}

#

Is plabel supposed to be string?

wooden badge
#

nonono

#

so basically what im doing is that im uploading an image, saving it, making a label/string for it and i want it displayed

#

and the error i got was none because the string wasn t computed

glass sandal
#

So plabel is supposed to be a javascript string right?

wooden badge
#

it s supposed to be a python string, do i need to make it js visible?

glass sandal
#

If yes , then do this :
var isattractive = "{{ plabel }}";

#

Notice how I added those "

wooden badge
#

Uncaught ReferenceError: Attractive is not defined

glass sandal
#

Did u add those "?

wooden badge
#

ooooh

#

you made it with ""

#

let me try

glass sandal
#

Yes

#

If it didn't work either , you can try :
if ("{{ plabel }}" != "None") var isattractive = "{{ plabel }}";

wooden badge
#

lol

#

using "" printed the label properly

glass sandal
#

So , it worked?

wooden badge
#

now basically the console.log worked

glass sandal
#

kk nice

wooden badge
#

let me see if it works in the function too

glass sandal
#

Ok try it

#

imma brb for a sec

wooden badge
#

because what i do is changing h3 to that string

#

oh kk

glass sandal
#

ok back

#

ok so you are using innerHTML right?

#

That must work

wooden badge
#

yeah im using that

#

quick question

glass sandal
#

?

wooden badge
#

the console points to a js file that is the old code used for it

#

like the js code didn t update with the changes

#

why is that so?

glass sandal
#

You have to setInterval

#

brb again sorry

wooden badge
#

uhhh

#

how do i do that then lol

#

i think the js got into cache

#

brb

glass sandal
#

back

#

For doing setInterval , you need two things . 1 : the Function you are gonna repeat , 2 : the time between repeating it each tim

#

time*

#

So you do it like :

#

(Instead of running function like myFunction() , do this :)

#
setInterval(myFunction() /* Your function */, 1000 /* Time in milliseconds */);
#

This will basically repeat your function every 1000 milliseconds which is 1 second

#

You can change it to any number

distant trout
#

can someone tell me how to use an api?

glass sandal
#

use requests library

distant trout
#

can i use it in flask?

glass sandal
#

Yes

distant trout
#

i want to add a spotify api to my website

#

oh

glass sandal
#

You want to make an API or use an API?

distant trout
#

use an API

glass sandal
#

ok so requests will do

#

If you need to use get method , use requests.get(url)

#

And It will show you the data

distant trout
#

i am still new to this, using API always requires a backend framework right?

#

such as flask/django/php

glass sandal
#

Ummmm , you can use it in Javascript but better in backend

#

Like posting in javascript is a pain

distant trout
#

yeah js syntax is hard for me 😓

#

anyways thank you!

#

time to get to researching 😄

glass sandal
#

np

#

Oh and I think you need to do requests.get(url).content

distant trout
#

yeah im reading the docs right now

#

for requests

glass sandal
#

k nice ! and gl

wooden badge
#

heya

#

@glass sandal i got back lol

glass sandal
#

lol

wooden badge
#

so imma start this again

glass sandal
#

lol k

#

So where were u?

wooden badge
#

just eating lol

#

but it's ok

glass sandal
#

lol

#

So your problem is fixed right?

wooden badge
#

halfway lol

#

`var isattractive = "{{ plabel }}";

function attf() {
console.log(isattractive);
document.getElementById("attractiveness").innerHTML = isattractive;
}`

glass sandal
#

Ok so you must do a setInterval right?

wooden badge
#

you said so

#

but how lol?

glass sandal
#

Add this the line after your function :

#
setInterval(attf(),100);
wooden badge
#

oh ok

glass sandal
#

100 is the time to restart the function in milliseconds

#

And the first argument is the function u wanna repeat

wooden badge
#

oooh

glass sandal
#

And don't forget to remove the console.log for production

wooden badge
#

nice

#

And don't forget to remove the console.log for production
@glass sandal of course

glass sandal
#

ok so try that

#

And remove the line where you start the function like attf()

wooden badge
#

alright so once this is up it should loop over the function

glass sandal
#

yes

wooden badge
#

oooh ok

glass sandal
#

every x milliseconds

wooden badge
#

function { console.log(isattractive); document.getElementById("attractiveness").innerHTML = isattractive; setInterval(attf(),100); }

glass sandal
#

nonono

#

Just replace setInterval with setTimout if you want to do it like this

#

timeout*

#

setTimeout is basically like setInterval but it doesn't repeat every time

native tide
#

Anyone here with the tiniest bit of experiencw with aiohttp?

glass sandal
#

But since you use it inside the function you are timouting

#

It loops

wooden badge
#

but what did you mean by deleting the attf() line?

glass sandal
#

Nah don't do it

wooden badge
#

ok

glass sandal
#

Cause you have setTimeout u need to run it first

wooden badge
#

little question

glass sandal
#

Feel free to ask

wooden badge
#

the <h3> should have like an onclick?

#

because im using

glass sandal
#

Nah

wooden badge
#

<h3 onclick="attf()">some text</h3>

glass sandal
#

It updates automatically

wooden badge
#

so what should i change the onclick to?

glass sandal
#

You want it to start updating when you click on the h3?

#

If yes , don't change it

strong glacier
#

can I ask a django problem here or use python help channel?

glass sandal
#

else , remove the onclick completely and put an attf(); in main.js

wooden badge
#

can it run over h3 without the need to click it?

glass sandal
#

@strong glacier Yes

#

@wooden badge Yes

#

If you put attf(); in main.js

wooden badge
#

oh ok

native tide
#

For the life of me I can't figure out why my company picked aiohttp over django or flask

glass sandal
#

lol I don't have any info on aiohttp so sadly I can't help

ashen sparrow
#

for asyncio ?

native tide
#

Me neither. That's the problem

glass sandal
#

Oof

native tide
#

Deadline for the project is the end of the month. Same day I lose my job lemon_long

glass sandal
#

Sorry , as I said I can't help since I don't know aiohttp

wooden badge
#

@glass sandal can js be cached?

#

because it seems so lol

glass sandal
#

Yes

#

Just Shift+F5

wooden badge
#

fuck

ashen sparrow
#

hard refresh

wooden badge
#

oh ok

strong glacier
#

UnboundLocalError at /new_entry/1/
local variable 'topic' referenced before assignment

#

What does that even mean?

glass sandal
#

Just global it

#

You are using a variable inside a function

#

Without globaling it

#

use global topic at start of function

strong glacier
#

How do I do that? I checked the line of code that shows the error but it looks fine (following a tutorial)

glass sandal
#

just add a global topic at the first line of your function

#

it'll work

strong glacier
#

Hmm but I'm following the guidelines of the book and that's not there and I don't know what that do actually

wooden badge
#

well this is nice

#

{{ plabel }}

glass sandal
#

Did it work?

#

@strong glacier As I said , add :

global topic

at start of function

#

You don't have to always follow the tutorial

strong glacier
#

like this? context = {'topic': global topic, 'form': form}

glass sandal
#

nonono

#

topic should be what it is

wooden badge
#

when i did
var isattractive = "{{ plabel }}";
and when calling console.log(isattractive); it spit out {{ plabel }}

glass sandal
#

Just add global topic at starting line of your function , after the line that has def

#

@wooden badge So what's the problem?

wooden badge
#

the "{{ plabel }}" is supposed to be a string lol

glass sandal
#

It is

strong glacier
#

def new_entry(request, topic_id):
global
"""Add a new entry for a particular topic."""
topic: Topic.objects.get(id=topic_id)

#

Like that?

glass sandal
#

When you add " it is a string

wooden badge
#

but it's not the string from the variable plabel

glass sandal
#

@strong glacier topic is an argument?

#

Then what is that :?

#

It must be "="

#

@wooden badge It must be

#

Cause you set timeout

#

Ohohoh

#

I understood something

#

You can add isattractive = "{{ plabel }}" to your function too

strong glacier
#

Oh wow I didn't see it yeah it was = so dumb 😅

glass sandal
#

XD

#

And remove the global

ashen sparrow
#

is there an API for github? like let's say I want to get total number of commits a user has made, is there an API for that?

strong glacier
#

Thanks!

glass sandal
#

np

#

As far as I know

#

this is the official

wooden badge
#

And remove the global
@glass sandal will try that

glass sandal
#

@ashen sparrow

ashen sparrow
#

aagh

glass sandal
#

@wooden badge Not you XD

ashen sparrow
#

i'll find more stuff over git, need to get the final count somehow ,thanks tho

glass sandal
#

np

wooden badge
#

Just added this to the .html

<script> . . . console.log(isattractive); document.getElementById("attractiveness").innerHTML = isattractive; </script>

if the <h3 id="attractiveness">text</h3> is also defined after that script i think it's overwritting text over tha value from isattractive

glass sandal
#

Nonononono

wooden badge
#

if i make the header empty

#

will it work?

glass sandal
#

In that function attf I doubt? add the isattractive = "{{ plabel }}";

wooden badge
#

In that function attf I doubt? add the isattractive = "{{ plabel }}";
@glass sandal working with the function has some problems so i tried with the <script>

#

yes that var is defined

glass sandal
#

Ok so define that function in that script

#

And as I said , it is defined but it isn't updated

#

You need to update the variable right?

wooden badge
#

yeah

#

`<script type="text/javascript">
function attf() {
var isattractive = "{{ plabel }}";

console.log(isattractive);
document.getElementById("attractiveness").innerHTML = isattractive;
setInterval(attf(),100);
}
</script>`

#

ok so i should put

#

the var inside

glass sandal
#

So add this :

isattractive = "{{ plabel }}";

in attf .
So like :

function attf() {
    isattractive = "{{ plabel }}";
    document.getElementById("attractiveness").innerHTML = isattractive;
    setInterval(attf(),100);
}
#

Just copy the altered function

#

And replace it with yours

wooden badge
#

oh ok

glass sandal
#

Oh nonono

#

I forgot

#

You must put the setInterval outside function

#

So

#
function attf() {
    isattractive = "{{ plabel }}";
    document.getElementById("attractiveness").innerHTML = isattractive;
}
setInterval(attf(),100);
wooden badge
#

ooooh set interval is outside

#

fuck

glass sandal
#

Yes

wooden badge
#

makes sense

glass sandal
#

yep

wooden badge
#

`<script type="text/javascript">
function attf() {
isattractive = "{{ plabel }}";
probability = "{{ probability }}";

console.log(isattractive);
document.getElementById("attractiveness").innerHTML = isattractive;
}

setInterval(attf(),100);

</script>`

glass sandal
#

Yes

wooden badge
#

spits out correct plabel Attractive in console

#

so it s good

#

but

#

Uncaught TypeError: document.getElementById(...) is null

#

it didn t update the <h3>

glass sandal
#

Ok so maybe the id is wrong

#

Try checking the id

wooden badge
#

same id tho

glass sandal
#

Ohoh

#

Move the script tag to end of the body tag

wooden badge
#

oh ok

#

it worked

glass sandal
#

Nice

wooden badge
#

so now that it's working with <script> in .html

#

how do i do the same thing but in main.js

glass sandal
#

Well , you better do it in html

wooden badge
#

like how do i make that script run at the end

glass sandal
#

Cause doing it in main.js would be a pain

#

(Or Idk how to do it the right/easy way)

wooden badge
#

LOL

#

ok

glass sandal
#

Let me know if it fixed

wooden badge
#

It is ok

#

now for the next problems :)

glass sandal
#

Oof

wooden badge
#

another quick question

glass sandal
#

kk

#

ask

wooden badge
#

can you reffer to an image in javascript as taking a directory path?

glass sandal
#

Well , you mean adding an image?

wooden badge
#

i think i didn t explain it properly

glass sandal
#

You mean adding an image right?

#

in javascript

wooden badge
#

i have this:
<form method="POST" enctype="multipart/form-data"> <input type="file" name="file" onchange="display(event)"> <input type="submit" value="Upload"> </form> <img src="/static/uploads/AlpharaFavAoiOgata.png" id="img" alt="Image" height="300"/>

glass sandal
#

Ok

wooden badge
#

the src is like the default one because i wanted it to have an image even when a file isn t selected

glass sandal
#

Oh okok

wooden badge
#

also im using this in main.js
function display(event) { var reader = new FileReader(); reader.onload = function() { document.getElementById('img').src = reader.result; } reader.readAsDataURL(event.target.files[0]); }

glass sandal
#

Why do you use FileReader?

wooden badge
#

so basically it s displaying the selcted image and then the image is submitted and saved to a directory

#

this is a force reload to the page

glass sandal
#

I don't know much about FileReader but ok

wooden badge
#

can i keep the image selected before the reload as the current image after the reload?

#

Why do you use FileReader?
@glass sandal what other function should i use

#

i used code from stackoverflow and after like 5 hours got it working lol

glass sandal
#

Oof

#

Ok tbh I don't know what does filereader do

wooden badge
#

don t worry about that part

glass sandal
#

Ok so you want to automatically reload the image right?

#

On upload?

wooden badge
#

so my image is
<img src="/static/uploads/AlpharaFavAoiOgata.png" id="img" alt="Image" height="300"/>
by default because i didn t know how to put an image when an image isn t selected

glass sandal
#

Oh ok

#

And btw

#

Use url_for

wooden badge
#

the js code modifies the scr to a file in that uploads dir

glass sandal
#

Instead of /static/

#

Hmmmm

#

I see

#

So it changes the src

wooden badge
#

Use url_for
@glass sandal i know about it but didn t use, i can change later

#

ok so my problem is

#

the image gets another scr when it s previewed

#

but after the reload it gets the default image

glass sandal
#

And there is something wrong with your js code , If I'm correct , the reader.result returns src from the client's computer . So like C:\users...

#

And that isn't in your server

#

That image*

wooden badge
#

nnonono

glass sandal
#

You have to save the image first , then you can change the src to it

wooden badge
#

it s the path related to the python routes.py directory

glass sandal
#

Is the image saved to your server?

wooden badge
#

so it s like gonna get the src static/uploads/image.jpg

#

Is the image saved to your server?
@glass sandal yes

glass sandal
#

So let me think for a second

#

So reader.result returns /static/uploads/image.png ?

#

or .jpg

wooden badge
#

yeah as far as i know

glass sandal
#

Ok so

#

It means that , your website collects the file

#

Saves it

#

And updates the src of image

wooden badge
#

yes

glass sandal
#

Right click on your image after uploading an image from your computer , and then goto it's link

#

See if it appears

#

or no

wooden badge
#

yes it does

glass sandal
#

And it is the right image right?

wooden badge
#

that s the default image

glass sandal
#

Oh

#

So the src doesn't change

wooden badge
#

the one put before uploading an image

dense slate
#

Is this in Django?

glass sandal
#

No flask

wooden badge
#

the src changes only before submitting. submitting the image refreshes the page so it returns the image to default

dense slate
#

Ok, might be similar. Aren't you supposed to use the model to refer to an image src in flask?

wooden badge
#

i got an idea

#

could i do like

#

if (document.getElementById('img').src != "/static/uploads/AlpharaFavAoiOgata.png") {
newimgpath = document.getElementById('img').src;
}

glass sandal
#

Actually

#

You have to put ==

#

Instead of !=

wooden badge
#

the negation in js is == ?

#

wtf

glass sandal
#

I mean

#

No

#

You want to check that if you are using the default image , change the path

wooden badge
#

i wanna say if the current src isn't the default then store the current(path from the image browsed) in a new variable

glass sandal
#

Oh

#

So yes

#

You can try that

wooden badge
#

and what i want now is to make another statement to change the image from default to that new variable

glass sandal
#

image.src = newPath; i guess

wooden badge
#

yeah kinda

#

im trying that

#

but it s weird because

#

if you do that it's gonna change the default as well

glass sandal
#

js is weird

#

And this makes it weirder

#

Ok so

#

That changes the default too?

wooden badge
#

ok what about if that if statement runs only when page reload?

glass sandal
#

Wdym , you mean the default image discards?

wooden badge
#

Wdym , you mean the default image discards?
@glass sandal you ll see what i mean

glass sandal
#

You don't want the default image to change?

#

I mean , you've set the image src = default image . you don't want to change that?

wooden badge
#

ok so my idea

#

`var newimgpath = ""

if (document.getElementById('img').src != "/static/uploads/AlpharaFavAoiOgata.png") {
newimgpath = document.getElementById('img').src;
}`

when this runs the newimgpath is empty but if the path of that image gets changed then the newimgpath is the path of that image

glass sandal
#

Hmmmmmmmm

wooden badge
#

what my idea is, can i now do

glass sandal
#

I mean , you can try?

wooden badge
#

(do the thing with on reload function)

if (newimgpath != "") {
document.getElementById('img').src = newimgpath
}

#

now

#

how do i make a function run at page reload

#

it was window.onreload or smth

glass sandal
#

Just do (function() {})

#

This runs on load

wooden badge
#

oh ok

glass sandal
#

(Not on reload , on load)

wooden badge
#

should hypothetically work

glass sandal
#

nononono

#

not function() {}

#

(function () {} )

#

You need those (

wooden badge
#

Uncaught SyntaxError: function statement requires a name

#

ooooh

#

ok