#web-development
2 messages · Page 69 of 1
probably not

those kind of pranks only work if the person doesnt copy the link
file:///C:/Users/Daniel/Documents/HTML/index.html
oh
thats the link for me
how do I get him that?
you have to send him the html page
like, you have to host the website somewhere and that costs money
well, theres free hosting services
there are free places to put static html
but for what you're doing it's a waste of time
Absolutely free web hosting with cPanel, PHP & MySQL for a stunning blogging start. Get free website hosting together with a free domain name at no cost at all!
github can do that, htmlpasta.com used to do that but died
but github is easier to use
https://pastehtml.com/ does exist, but requires an account
not gonna help you with that one (github) because there are lots of resources online to help with it
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
Close the loop on your developer cycle by automating testing of your website in Microsoft Edge with Microsoft WebDriver
sorry for the huge block
Hello all. Can someone recommended me a book/site/app from where I can study Django.(level is begginer)
django docs are honestly great
do you have experience with setting up python / virtual environments?
yeah follow tutorial on Django's website
or watch tutorial series by Cory Schafer(where I learnt basics)
@native tide S460 was lookin for help 🙂
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.
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?
The plan I have is that it only displays current day reservations, and old ones can be found in a different view
moving data from model to another model isn't a good way, I would go with different views with different querysets etc
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?
You can store everything in one model and handle by specific filters. E.g. that filter will be helpful if you would like to have filtered reservations by specific date:
https://docs.djangoproject.com/en/3.0/ref/models/querysets/#date
I don't know your code so can't help too much. :D
Models/Views
but anyway you should firstly follow some good tutorial/video about and how to handle filters in Django
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 = '/'
the field reserve_time and date look confusing, If both of them relate to date of reservation then having one DateTimeField would be better
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
and also I recommend you to get interested with that method
https://ccbv.co.uk/projects/Django/3.0/django.views.generic.list/ListView/#get_queryset
(PS. it's a great site if u want to override bult in views)
ListView in Django 3.0.
Render some list of objects, set by `self.model` or `self.queryset`.
self.queryset can actually be any iterable of items, not just a queryset.
so it should be DateTimeField instead of TimeField
with get_queryset method you may easily change the default queryset in view, what you want
Oh I see. quereyset holds the info of each instance of reservation right?
yeah, the default is Reservation.objects.all()
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?
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?
https://flask-wtf.readthedocs.io/en/stable/form.html
See the first example there @wind walrus and construct your save path with the user's folder name too
f.save(os.path.join(
app.instance_path, 'photos_' + user.coolfoldername, filename
))
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'
hey guys how can i deploy my django web app on a ubuntu server ?
Don't you just like, run it?
i really do wish it was that easy.
@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.
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.
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?
I was able to create an ok looking website just by looking up the proper bootstrap classes for the contents of a given section
has anyone used django with docker on ubuntu server ?
Yes?
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:
- make a dockerfile that installs your dependencies and copies the server files in and does runserver
- build the dockerfile and push to a container registry somewhere
- 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
docker has a quick guide for django too: https://docs.docker.com/compose/django/
alternatively for step 1, don't use runserver on prod....
true true, do the gunicorn stuff
i know this is web dev but where can i show of my work
@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
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
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
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!
@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
thanks, any good sources to learn? i am using udemy for python atm
uhhh
actually one sec
i think i may have something somewhere
https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics heres a good place to start
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
it does
most of the time
any good one will cost money
theres some free services that can kind of host your site
i only know that sites like godaddy sell domains
i see! am i the only one who can work on the website?
like is it somehow password locked?
i mean
you're the one with the code
anyone can steal the frontend of a site
but its the backend that actually matters
its not about stealing, but more about people making changes on my website 😄
like hacking a social media profile and changing the bio
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
I see, i have to learn some stuff about that
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
Depends, if you are using MySQL you need to make sure you sanitize all input
@solar crag
The templates and {% extends “base.html” %} feature is Flask specific right? It’s not a HTML feature
@wind walrus no, it is Jinja specific
In which case, if you were to create a website with purely frontend, how would you do sth like templates?
Oh
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
@solar crag check this: https://realpython.com/prevent-python-sql-injection/
So if you were to use JavaScript as both frontend and backend for example
You could still use the templates?
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
Yeah nodejs
I usually use SPA frameworks when I use javascript (or typescript) backend, some of these frameworks are React, Vue and Angular
These are frontend frameworks though
thanks
Jinja is modeled after Django's template engine
Oh wow okay thank you
You could also use a static site generator if you don't plan on having a backend but still want some content management tools
Yes
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)
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?
Why run inside Gunicorn instead of standalone?
The site in general or the script?
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.
how i can fix this? https://hastebin.com/qiluroyowa.sql
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)
Hey, I need some help with Selenium anyone got a minute? If so, please @ me
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. 🙂
Any of u can help me plz
In Django or Flask?
In making my First Web page
Or selenium?
Django
What is the prob?
We use views to do python functions in specific urls
And you can return html pages by it
Wdym by linking a page?
By giving link of 2nd page on 1st page
Use an "a" tag
Like <a href="https://www.google.com "> the link</a>
Okay thanks
np
Can i again catch u up when needed?
Well , I may be busy but maybe yep
Okay thanks😊
np
If i have a html file with a bunch of variables in it, how can i have flask read that file and the variables
hej
does anyone else get a blank page when redirecting on any browser other than firefox with django.http.HttpResponseRedirect?
is it okay to show someone my cookiekeader
@scarlet wind never do that
why? D:
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
I am talking about in the network inspection tab, where it says set-cookie
under response headers
oh
is that okay?
trying to look for it in my inspect element
I think you have set something to a cookie first
do you mean this?
no, in the network tab; click on the html page under names and then go to headers
I guess it's safe, just don't send the cookie
@ruby fjord the cookie didn't have any personal data inside it
Isn't that all that cookies are for ?
this has examples of the set-cookie header https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cookie
is the set cookie header unique to each individual server or cookie?
what if I clear my site data, will it be different?
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.
I am a senior developer. I am good at django development.
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.
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
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
how can i integrate the usage of scss or sass on my django project
@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.
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
@faint pulsar Jon Duckett has 2 books
js and jquery
html and css
ive heard they are good
@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.
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.
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
ty, yeah, I nuked my db once on accident and am super careful now
You shouldnt mess your migrations as a whole if you dev on a separate branch
You can also unaply migrations
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.
Yeah, config and deployement are the hard part the tutorial skip throughs usually
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
It is a real problem people argue about for years
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
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
Ok, I will be rewriting my project over the next few days.
Ty very much for everyone's late night help.
Is there something like the debug panel in Django, in flask?
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
haha, I figured that's why I was getting more responses now.
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
anyone around for a django question?
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
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.
what exactly is it that you're trying to do at a high level?
stop the need for a user to reload the page after downloading a folder
i'm using django FileResponse to provide the download,
well, you want to send the file as an attachment?
i.e you want them to download a .zip?
yeah
you need to send an as-attachment header somewhere
1s
Here's the SO post I've used to solve that problem https://stackoverflow.com/questions/36392510/django-download-a-file
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
hm - that doesn't actually look 100% right to me. But if you google around for similar things, it's definitely a solvable problem.
i'm currently using attachment; filename
i'll switch to inline
hmm no change
i'll look more into it though
I've solved this exact thing before. I'll have a look at how I did it, just need to find the project
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
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
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
That sounds like it would be easiest solved with JS. Not entirely sure. SEeems like a weird thing to want to be doing
yeah it's because i'm updating the page state as the user goes through certain tasks
I keep getting an error
when trying to display information from a database onto a page
can anyone help
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
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%}
That would be comparing a user to a username
Yup, I wanna compare a user against a username
why would you do it in the template instead of passing a value?
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
@bleak bobcat what's the best way to compare a user in relation to models?
z̯̯͡a̧͎̺l̡͓̫g̹̲o̡̼̘
Whatever is unique in that model, id for example
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?
I'm not sure about the answer; but I think taking a look at that could help : https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.ManyToManyField
you could make a another model just for friends and have a ForeignKey relationship(one to many) with person
go ahead
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)
i put it there because my real code is a long dict
Guys what would u do in Django/Flask if you are bored?
I have no ideas to make any websites
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
no
contribute to pre-existing django projects
Oh
@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
i have a foreign key in my model how do i handle that ?
and can u provide some examples ?
@glass sandal the upcoming jam is based on django
Oh nice
check #announcements
But what about like another things
I mean
We don't have site jams always
Then is it an alternative?
@worn aurora fetch the foreginkey model instance first and then assign it
@glass sandal it is a site jam, django it is, plz read #announcements
kk
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
whats that error?
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!
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:
the error from elsewhere, its saying there is no key called type
check your parent_page.add_child method
is base.html in same app ?
and are you rendering home.html? and does base.html have a block named "content" in it?
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'
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?
You can override the save method to implement your calculations
Or can use Django signals too,like post_save
It's best to have signals in their own separate file
Oh ok gotcha
And use a connector
just import it into models then?
There are pretty good YouTube vids too which cover Django signals incase the docs are confusing
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>
you could optionally make the if-else query at the html with the template language i think...
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
BTW, I found my mistake. I wasn't storing cookies when I make a request XC
https://discordapp.com/channels/267624335836053506/366673702533988363/730835069933060108
I figured mine out too... I had a wrong import -_-
:p
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?
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
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
thanks!
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
right ☝️ to reiterate, don't combine react with django templating (too much)
Django models. How to block removing 0 from numbers? If I have 10.00 django removing last 0 and I get 10.0 :(
Floats don't have a number of decimal places associated with them. You can change how many places you want when displaying them though
You are not allowed to use that command here. Please use the #bot-commands channel instead.
f"{n:.3f}" -> 10.000
thanks
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
import datetime, datetime.now ?
something like that, i forgot the exact lines
it wont be dynamic withflask tho
why not
Hello
hi
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)
whats the website
if they've added a captcha its very apparent that they dont want people scraping and automating that
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
pythonand 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
i would just solve the captchas and then send the cookies together with the requests
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.
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 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
you can do alot to detect bot activity on sites
^ true, and that's because lots of people use the same tools for scraping
defcon has some amazing talks on fighting back against web scrapers and spiders
@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?
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
did you use proxies or your own IP for all connections?
My own IP
that's the problem then
Really? But it's the same as if I was just visiting the website and quitting
it's a little illegal
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
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!
it's not
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?
I also don't know, what you do is not illegal but the rules its illegal so its illegal 😛
check your inbox
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?
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
React and ReactJS are the same thing, Express is a nodejs framework, you use it on backend with javascript
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
I suggest asking React questions in a frontend development server
Let me look for one
Sent you the invite link through DM!
what should one learn first js or html and css
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
wats diff between normal html and html5
complex question
like python2 and 3?
can I sign up for code jam or do I need to qualify
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
is react more powerful than css and html
it's not one or the other
I think so
cause ive heard react and django is a powerful combo
yh
you don't learn either/or. Trying to learn react without first learning html would be weird
I use Html, CSS and django I rlly want to learn react
though it's true that when you use react, you no longer write raw HTML
lol wats diff between react and reactjs
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"
thats wat i meant
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
what's json
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
ah OK
many things use json
thanks
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
ok thnx
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
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.
Is there a big difference between which database server I learn Django with?
for learning, generally no
they all have your basic features that you'd expect for doing database things
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())
Anyone know if theres a limit to how many instances of a model you can have?
or at least how many is reccomended
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
but is it good practice to clear it out every once and a while or does it not matter?
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.
gotcha, thanks!
Getting 404 not found for 2nd class Notedetailedview
does the serializer field for "detail" match the name of an attribute to a model? Idk, im a noob to django rest
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
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
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?
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
Also check out #728034538806312970
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 ?
thanks @icy wasp
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!
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?
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
Is there a panel like Djangos debug pannel in Flask?
im not familiar with djangos debug panel but usually you just write FLASK_DEBUG = 1
in cmd
cuz theres no panel
Well I mean maybe an external library for flask
https://flask-debugtoolbar.readthedocs.io/en/latest/
This actually could be what I need.
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'
nevermind solved it with "owner__username" (see https://stackoverflow.com/questions/62638087/field-id-expected-a-number-but-got-natsu-django)
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
Hi i am really new to this and i was just wondering if anyone could check out my question on Stack Overflow?
Here's the link if anyone's interested https://stackoverflow.com/questions/62835831/noreversematch-at-result
Guys don't u get bored making websites?
how do i reference a variable created in python with flask api to a javascript variable in main.js
tried it before, will try with different names
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?
to be honest i would try something before figuring that
so for example you can print in terminal using console.log(variable) right?
Right
`var isattractive = {{ plabel }};
function attf(event) {
console.log(plabel)
document.getElementById("attractiveness").innerHTML = isattractive;
}`
correction
So I don't see any problems here I guess?
i saw it as soon as i posted lol
lol
the console.log should spit out the string in the running terminal?
ummmm?? not in terminal . just press F12 if you are in Chrome then open the Console tab
And you'll see values there
ooh
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
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
Did u fix it?
should i explain more of what im doing?
I mean
you must console.log(isattractive)
@glass sandal i did so
i did not lol
Goto your HTML file and add a script tag before referencing to your main.js
ok
and insert the function used?
to {{plabel}}
oh ok
`<script type="text/javascript">
var isattractive = {{ plabel }};
function attf() {
console.log(isattractive)
document.getElementById("attractiveness").innerHTML = isattractive;
}
</script>`
k let s see
ok
And did you remove the var isattractive = {{ plabel }}; in main.js?
If no , remove it
oh ok i ll do that
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?
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
So plabel is supposed to be a javascript string right?
it s supposed to be a python string, do i need to make it js visible?
If yes , then do this :
var isattractive = "{{ plabel }}";
Notice how I added those "
Uncaught ReferenceError: Attractive is not defined
Did u add those "?
Yes
If it didn't work either , you can try :
if ("{{ plabel }}" != "None") var isattractive = "{{ plabel }}";
So , it worked?
now basically the console.log worked
kk nice
let me see if it works in the function too
?
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?
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
can someone tell me how to use an api?
use requests library
can i use it in flask?
Yes
You want to make an API or use an API?
use an API
ok so requests will do
If you need to use get method , use requests.get(url)
And It will show you the data
i am still new to this, using API always requires a backend framework right?
such as flask/django/php
Ummmm , you can use it in Javascript but better in backend
Like posting in javascript is a pain
k nice ! and gl
lol
so imma start this again
halfway lol
`var isattractive = "{{ plabel }}";
function attf() {
console.log(isattractive);
document.getElementById("attractiveness").innerHTML = isattractive;
}`
Ok so you must do a setInterval right?
oh ok
100 is the time to restart the function in milliseconds
And the first argument is the function u wanna repeat
oooh
And don't forget to remove the console.log for production
nice
And don't forget to remove the console.log for production
@glass sandal of course
alright so once this is up it should loop over the function
yes
oooh ok
every x milliseconds
function { console.log(isattractive); document.getElementById("attractiveness").innerHTML = isattractive; setInterval(attf(),100); }
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
Anyone here with the tiniest bit of experiencw with aiohttp?
but what did you mean by deleting the attf() line?
Nah don't do it
ok
Cause you have setTimeout u need to run it first
little question
Feel free to ask
Nah
<h3 onclick="attf()">some text</h3>
It updates automatically
so what should i change the onclick to?
can I ask a django problem here or use python help channel?
else , remove the onclick completely and put an attf(); in main.js
can it run over h3 without the need to click it?
oh ok
For the life of me I can't figure out why my company picked aiohttp over django or flask
lol I don't have any info on aiohttp so sadly I can't help
for asyncio ?
Me neither. That's the problem
Oof
Sorry , as I said I can't help since I don't know aiohttp
fuck
hard refresh
oh ok
UnboundLocalError at /new_entry/1/
local variable 'topic' referenced before assignment
What does that even mean?
Just global it
You are using a variable inside a function
Without globaling it
use global topic at start of function
How do I do that? I checked the line of code that shows the error but it looks fine (following a tutorial)
Hmm but I'm following the guidelines of the book and that's not there and I don't know what that do actually
Did it work?
@strong glacier As I said , add :
global topic
at start of function
You don't have to always follow the tutorial
like this? context = {'topic': global topic, 'form': form}
when i did
var isattractive = "{{ plabel }}";
and when calling console.log(isattractive); it spit out {{ plabel }}
Just add global topic at starting line of your function , after the line that has def
@wooden badge So what's the problem?
the "{{ plabel }}" is supposed to be a string lol
It is
def new_entry(request, topic_id):
global
"""Add a new entry for a particular topic."""
topic: Topic.objects.get(id=topic_id)
Like that?
When you add " it is a string
but it's not the string from the variable plabel
@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
Oh wow I didn't see it yeah it was = so dumb 😅
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?
Thanks!
And remove the global
@glass sandal will try that
@ashen sparrow
aagh
@wooden badge Not you XD
i'll find more stuff over git, need to get the final count somehow ,thanks tho
np
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
Nonononono
In that function attf I doubt? add the isattractive = "{{ plabel }}";
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
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?
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
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
oh ok
Oh nonono
I forgot
You must put the setInterval outside function
So
function attf() {
isattractive = "{{ plabel }}";
document.getElementById("attractiveness").innerHTML = isattractive;
}
setInterval(attf(),100);
Yes
makes sense
yep
`<script type="text/javascript">
function attf() {
isattractive = "{{ plabel }}";
probability = "{{ probability }}";
console.log(isattractive);
document.getElementById("attractiveness").innerHTML = isattractive;
}
setInterval(attf(),100);
</script>`
Yes
spits out correct plabel Attractive in console
so it s good
but
Uncaught TypeError: document.getElementById(...) is null
it didn t update the <h3>
Nice
so now that it's working with <script> in .html
how do i do the same thing but in main.js
Well , you better do it in html
like how do i make that script run at the end
Let me know if it fixed
Oof
another quick question
can you reffer to an image in javascript as taking a directory path?
Well , you mean adding an image?
i think i didn t explain it properly
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"/>
Ok
the src is like the default one because i wanted it to have an image even when a file isn t selected
Oh okok
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]); }
Why do you use FileReader?
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
I don't know much about FileReader but ok
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
don t worry about that part
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
the js code modifies the scr to a file in that uploads dir
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
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*
nnonono
You have to save the image first , then you can change the src to it
Is the image saved to your server?
so it s like gonna get the src static/uploads/image.jpg
Is the image saved to your server?
@glass sandal yes
So let me think for a second
So reader.result returns /static/uploads/image.png ?
or .jpg
yeah as far as i know
Ok so
It means that , your website collects the file
Saves it
And updates the src of image
yes
Right click on your image after uploading an image from your computer , and then goto it's link
See if it appears
or no
And it is the right image right?
that s the default image
the one put before uploading an image
Is this in Django?
No flask
the src changes only before submitting. submitting the image refreshes the page so it returns the image to default
Ok, might be similar. Aren't you supposed to use the model to refer to an image src in flask?
i got an idea
could i do like
if (document.getElementById('img').src != "/static/uploads/AlpharaFavAoiOgata.png") {
newimgpath = document.getElementById('img').src;
}
I mean
No
You want to check that if you are using the default image , change the path
i wanna say if the current src isn't the default then store the current(path from the image browsed) in a new variable
and what i want now is to make another statement to change the image from default to that new variable
image.src = newPath; i guess
yeah kinda
im trying that
but it s weird because
if you do that it's gonna change the default as well
ok what about if that if statement runs only when page reload?
Wdym , you mean the default image discards?
Wdym , you mean the default image discards?
@glass sandal you ll see what i mean
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?
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
Hmmmmmmmm
what my idea is, can i now do
I mean , you can try?
(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
oh ok
(Not on reload , on load)



