#web-development
2 messages ยท Page 26 of 1
yeah last pass
just for grins... try removing the conditionals in the body of the loop, and see if it graphs it all, willy nilly
the if's?
yah
ok
maybe the compares are going sideways somehow
yeah same thing
that suggests to me that there isn't as much data to iterate over as you are anticipating
there definetly is, because im displaying the data that's neeeded in <h3> tags
on each iteration of the loop
nods
gotta be something wrong with how you're setting up the chart then
all else assumed to be fine as it is
(might want to put your conditionals back in there as they clearly weren't a source of trouble)
yeah i put them back
i also tried, making each chart have a unique id and still didnt work
do you have to specify ahead of time how many columns in the chart?
um
dont think so?
Highcharts.chart('chart', {
title: {
text: chart_brand
},
subtitle: {
text: 'Title'
},
yAxis: {
title: {
text: 'Price'
}
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 0
}
},
series: [{
name: chart_sku,
data: chart_data
}],
responsive: {
rules: [{
condition: {
maxWidth: 800
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
</script>```
yeh im lost for the time being
I would get hold of the doc for highcharts (it's out there somewhere) and go over it with a fine toothed comb alongside that invocation
You might be generating a series of single column charts, until you generate the last one and it displays
I have my first MVC flask app, and a basic auth module model's particular method is giving me effing fits
do you know flask/flask-login?
it even places the chart under the h3 of the first iteration in the loop, but with the data from the last iteration
yeah that's a clue
nah i havnt worked with flask auth at all sorry
it's great fun lol
You're probably better off in a help channel for a question regarding selenium
i've built an application as a standalone CLI that can generate JSON files among other things. i'm wondering what's the best way to go about building a Django UI layer for that application? call the CLI directly, integrate the CLI's entry point into a model, or...? i'm leaning towards the second approach, but maybe there's another approach i'm not thinking about?
@wise pumice the general answer is that you would put your core functionality in a library. then both your CLI and your web app import the same library. they just differ in their interfaces.
that sounds like a better approach. thanks.
If i want a web developer teammate , is it allowed to ask in this channel?
i asked last night, with no luck, so im going to see if anyone else knows.
how can i go about looping over data and having more then one highchart on a page
from what im doing it will place the highchart in the position of the first iteration of the loop, but with data from the last iteration
also is there an easy way pass variable from one template to another
Anyone here know their way around html/css much? need some help with getting my fonts to "activate".
Using fonts off google fonts and embedding the import link into my css if that helps
How I can do something like this?
I have two bootstrap cards and I want to drag and drop it.
If you go to your GitHub profile page, you can customize your pinned repositories at the topright corner of the pins area
Once you selected the ones you want to show, you can drag them around to rearrange them
@patent cobalt I know, but I want to recreate it.
@hybrid citrus No, I want to recreate the drag and drop system
Where?
There are some examples too
from flask import Flask, request, jsonify, Blueprint
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
bp = Blueprint('api', __name__, url_prefix='/api')
bp.route('/', methods=('GET'))
def index():
return jsonify({'msg': 'hello'})
init.py
app.register_blueprint(api.bp)
app.register_blueprint(feature.bp)
app.add_url_rule('/', endpoint='index')
return app
anyone can tell me why i'm getting a 404
not found
request localhost:5000/api
Can someone help me please
no such table: django_session
I have this issue everytime i try to go to the admin page
using Django
did you migrate ?
and makemigrations
and make sure you have django.contrib.sessons in your installed apps and resync db
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: django_session
[21/Jun/2019 23:53:06] "GET /admin/ HTTP/1.1" 500 197224
@native tide
There
I can't paste all the error cause discord doesn't allow too many words
I solved it
I just have to migrate
Thanks @native tide
Anyone know how to pass variable from parent.html to child.html with jinja/flask
can be done with url_for without adding it to the actual url
@native tide Because that blueprint is empty, bp.route() must be used as a decorator
Hi all
I have a problem with Django database.
I've made some changes to my models so now they have different fields. I've made sure I had replaced them everywhere. Gladly, there are not many places since it's a tutorial project.
So since I've had objects in my DB, I decided to reset it. I've deleted the db.sqlite3 file and migrations.
Then I made new migrations and started a new DB.
But now every time I run server it gives me this error:
django.db.utils.OperationalError: no such table: catalog_pizza (Catalog is an application and Pizza is a model it has)
Did I forget something or was it a mistake to delete the database?
this helped
https://stackoverflow.com/questions/40844785/django-migrate-django-db-utils-operationalerror-no-such-table
how do I create many <p> with Id tags. Let me explain. Let's say you have a comment system right. And You use AJAX right? And whenever you comment something it appears in the comment section. But you use id to display the data from the ajax in the <p> tag. the problem is that whenever you wanna comment something new, you will change the post you earlier created.
like let me show you a gif
https://gyazo.com/cdcdd746e668748dd3be34b4c78a1d9b
@floral seal : isn't
from flask import Flask, request, jsonify, Blueprint
import os
from models import Feature_Schema, Feature
bp = Blueprint('api', __name__, url_prefix='/api')
bp.route('/api/features', methods=('GET'))
def index():
all_features = Feature.all()
return Feature_Schema.jsonify(all_features)
That's still not a decorator
what do you mean?
@bp.route(...) < decorator
bp.route(...) < not a decorator, normal function call
also like this your route's path will end up as /api/api/features, which I doubt is what you want
@floral seal : yea, thats right.
which i remove?
from bp.route() right?
yea, thank you.
๐
wdym?
Never used it, sorry
No problem, thanks anyway.
What are the best payment plugins for US based geocities/neocities site? Subscription management may be a factor here, but perhaps not necessary.
There is option overload.
Is it even recommended to use Neocities for business? Hosting is free.
What features must be added in a Portfolio & Blog website and should i add user registration ?
How to make a contact form in a django? I know how to make forms but i just want to let the user to type his email and his discussion then it would be sent to my email or admin page
I have a main problem here
How to connect the css file into html file into the templates directory that starts with block content cause all of my css files are connected to the base file and i want to connect it to about page as an example so every page have a different style but the homepage gonna be the base one.. Every time I try to connect css file nothing happen into the specific page I mentioned
Anyone?
please mention me if you know the solution
{% extends "blog/base.html" %}
{% load static %}
{% block content %}
<link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}">
<center>
<div class = "contact-form">
<h1>Contact</h1>
<p>I am always ready to serve you</p>
<br>
<br>
<form>
Subject:
<input type="text" name="subject" required> <br> <br>
Email:
<input type="email" name="email" required> <br> <br>
Discussion:
<input type="color " name=" disc" required> <br> <br>
<input type="submit" name="button" >
</form>
</div>
</center>
{% endblock content %}
Like this it doesn't load the static files
and it doesn't give an error or something so please someone tell me what shall i do
I am using Django
Hey guys
I have this two models
class User(Base, UserMixin):
__tablename__ = 'user'
id = Column(Integer(), primary_key=True)
created = Column(DateTime(), default=datetime.now)
email = Column(String(255), unique=True)
username = Column(String(255))
password = Column(String(255))
last_login_at = Column(DateTime(), onupdate=datetime.now)
current_login_at = Column(
DateTime(), default=datetime.now, onupdate=datetime.now)
last_login_ip = Column(String(100))
current_login_ip = Column(String(100))
login_count = Column(Integer())
active = Column(Boolean())
confirmed_at = Column(DateTime())
def __init__(self, username: str, email: str, password: str):
self.username = username
self.password = password
self.email = email
def __repr__(self):
return f"{self.username} {self.email}"
class UserSchema(ma.Schema):
class Meta:
fields = ("username", "email")
class Client(db.Model):
__tablename__ = 'client'
id = Column(Integer, primary_key=True)
created = Column(DateTime(), default=datetime.now)
email = Column(String(255), unique=True)
username = Column(String(255))
if i want to make a relationship between then with sqlalchemy
i have to create a third table like this?
What libraries are recommended for bi-directional communication in Django? Is Django Channels good?
is there a good guide on how to implement gulp include
is there a way to configure sql alchemy in flask in a way that the app can run even when the server has no connection to the database? (its an external data source that might not be up 24/7)
it can run without connection but if you query anything while db's off you'll get 404
the server isnt starting tho
can you send error trace
1 sec
sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway
which makes sense since I changed the remote host to force an error, but that's literally what i'll get if its offline too
(I connect to the sever through an ssh tunnel, then connect to their database in a SQL_ALCHEMY_BINDS config)
and then if this ssh connection fails I cant really configure a proper mysql connection since I need to use the tunnel local bind port (afaik its different on each single connection)
then if I just surround both the tunnel and the db connection in a try except, when I try to do a query it's obviously complaining about that bind not existing (which makes sense), will it attempt to reconect on its own?
this being the error when querying:
AssertionError: Bind 'external_souce' is not specified. Set it in the SQLALCHEMY_BINDS configuration variable
Hey guys, was wondering if I could get some opinions on if the way I use โarticlesโ really matters, basically Iโve found that when using multiple articles, the gaps between each are larger than I would prefer and padding/margins can only change so much, therefore would it be โbadโ to chuck everything in the one article and separate them with headings or is it good practise to create new articles for each paragraph? I prefer the more compacted look of everything when it is in the one article.
like this...
or this?
Anyone for learning Python/Django in pair ?
Hi all. Can't find material I need.
I want to have a CharField that's limited to a certain length (as in required to be of specific length) and can only have certain symbols.
Googling it only gives me basic articles on what are fields and how to use them. I can't find a list of possible options.
Hey guys, a few months ago I started to learn some stuff with Django, but I didn't really like it. Because in my opinion it's like too much stuff that you have to do to be able to certain small stuff. So I was wondering if there is something that gives you the possibility to like use JS to connect with your HTML & CSS files. And use python as backend which is connected with your JS.
@hoary spruce so what's the question?
The last two sentences lol
And what if I wanted to go more towards chromium based applications?
Hey guys, I have a weird thing in my form.
On Django.
It renders fine but for some reason it has type="hidden"
Which makes it invisible on the page
It's definitely not in my .css, I tried rendering the page without it.
Can someone please help me figure it out?
Django will render a csrf_token input field automatically and label it as hidden, but you're saying your whole form is hidden? How are you rendering it
Ok, so I manage to make it work but I had to use a function instead of a class.
1 sec, gonna post it
Trying something out
np
class Cart(TemplateView):
template_name = 'shop/cart.html'
def get(self, request):
form = OrderForm()
return render(request, self.template_name), {'form': form}
def post(self, request):
form = OrderForm(request.POST)
if form.is_valid():
order_name = form.cleaned_data['order_name']
args = {'form': form, 'text': order_name}
return render(request, self.template_name, args)
Case 1
def cart(request):
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('')
else:
form = OrderForm()
return render(request, 'shop/cart.html', {'form': form, 'text': 'order_name'})
Case 2
@indigo kettle So in case 1 it renders this:
<button type="submit">Submit</button>```
And in case 2 it renders properly
<input type="hidden" name="csrfmiddlewaretoken" value="...">
<tr><th><label for="id_order_name">Your name:</label></th><td><input type="text" name="order_name" maxlength="100" required id="id_order_name"></td></tr>
<button type="submit">Submit</button>
Am i missing something here?
Or is it just not the right way to have a form view?
How are you rendering the form in your template?
Did you render them in both cases like {{ form.as_table }}
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
The simplest possible way
I'm learning backend logic so I haven't really touched the template yet
you can always render the fields manually as well, which is what I have always done
For you that might look like
<form method="post">
{% csrf_token %}
{{ form.order_name }}
<button type="submit">Submit</button>
</form>
I have always used functional views as well, so I'm not sure why the class based view didn't render the form the same way :/
Yea, it's frustrating. But I still managed to make it work nonetheless. ๐
I have a further question if you don't mind.
go for it
The lesson I'm following is using class based views and it manages to output your input on the page once you press the button but somehow it doesn't work in regular view
Here's full body
<div class="container">
<form method="post">
{% csrf_token %}
Your name: {{ form.order_name }}
<p><button type="submit">Submit</button></p>
</form>
<h2>{{ order_name }}</h2>
</div>
If you look at class based view which doesn't work for me (but works on the video I'm watching), every time you put something in the field and press the button, it reloads the page with your previous input below
And if you look at my regular view, it is there but it doesn't work.
If I put in this line:
return HttpResponseRedirect('', {'form': form, 'text': 'order_name'})
it throws an error
sure, so you'll just have to edit your view to return the order_name in the context
Ok... how do I do that?
yeah, sorry just a sec
def cart(request):
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
order_name = form.cleaned_data['order_name']
else:
form = OrderForm()
return render(request, 'shop/cart.html', {'form': form, 'text': order_name})
This is very similar to what you had before
I tried doing it this way:
def cart(request):
if request.method == 'POST':
form = OrderForm(request.POST)
context = {
'text': order_name
}
if form.is_valid():
return HttpResponseRedirect('', context)
else:
form = OrderForm()
return render(request, 'shop/cart.html', {'form': form})
That might also work, but you have to define order_name first
Oh, ok, I got you wrong XD
Hm
I'm forgetting something herer
It doesn't show the result below the form
But if I change it to form.order_name, it gives me another form which has the value I put in the first one
So it gets the value, just won't render it as text for some reason
in your template, you have to make sure you're using the correct context variable
np, I thought that might come up
forgot to rename it in the template
yep
Thanks alot, bro! You saved me some precious time ^_^
you're welcome ๐ glad it's figured out
is it possible to run a webapp parallel with a discord bot get github event triggers to the flask webserver and then send em via bot?
@marsh canyon since discord.py is async you should use a async-compatible server instead of flask; try quart maybe?
yes
okay thanks
is there a way to pass a variable from one flask page to another
Cookie?
i haven't looked into cookies yet, can i set a jinja variable in the cookie and access it in another page?
Oh, i guess i didn't understand you correctly
I thought you meant passing variable to user so you can access it on another page
well i kind of am
for example i have a product page
which i want to be able to click a link and pass data from the initial page to the second, so i can have a page dedicated to more info about the product
i have it working, but am only able to display the data sent via the url_for
How long its takes to undermine django?
really need help with sending files to the user web client, so I basically want him to download a file on click
don't know how to actually send a file to him, can't seem to find a proper page in documentation
in Django is it possible to refactor this ?
def resolve_collection_detail(*_, id)
collection = Collection.objects.get(id=id)
# collection.items = [[UUID('b.............8...............')]]
items = [i for i in Album.objects.filter(id__in=collection.items)]
collection.items = items
return collection
Collection model has items field which consists of ArrayField(models.UUIDField())
Hey guys, I have a really annoying problem with my Flask app. If anyone is willing to take a look at this I would really appreciate it: https://stackoverflow.com/questions/56739519/cookies-not-being-set-even-with-cors-enabled
is there any better way to return a response and render a template, than this? https://stackoverflow.com/questions/43688011/how-to-get-django-to-return-both-an-httpresponse-and-render-a-different-template
Like, I am using the solution from the previous link I've posted, and want to render a template too
OSError at /
[Errno 22] Invalid argument: 'C:\\Users\\Deepak\\Envs\\dummy\\lib\\site-packages\\django\\contrib\\admin\\templates\\<h1> helloworld <\\h1>'
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 2.2.2
Exception Type: OSError
Exception Value:
[Errno 22] Invalid argument: 'C:\\Users\\Deepak\\Envs\\dummy\\lib\\site-packages\\django\\contrib\\admin\\templates\\<h1> helloworld <\\h1>'
Exception Location: C:\Users\Deepak\Envs\dummy\lib\site-packages\django\template\loaders\filesystem.py in get_contents, line 23
Python Executable: C:\Users\Deepak\Envs\dummy\Scripts\python.exe
Python Version: 3.7.3
Python Path:
['C:\\Users\\Deepak\\Desktop\\deepshop',
'C:\\Users\\Deepak\\Envs\\dummy\\Scripts\\python37.zip',
'C:\\Users\\Deepak\\Envs\\dummy\\DLLs',
'C:\\Users\\Deepak\\Envs\\dummy\\lib',
'C:\\Users\\Deepak\\Envs\\dummy\\Scripts',
'c:\\users\\deepak\\appdata\\local\\programs\\python\\python37\\Lib',
'c:\\users\\deepak\\appdata\\local\\programs\\python\\python37\\DLLs',
'C:\\Users\\Deepak\\Envs\\dummy',
'C:\\Users\\Deepak\\Envs\\dummy\\lib\\site-packages']
Server time: Tue, 25 Jun 2019 11:48:17 +0000
this is the problem
line 23
send
Exception Location: C:\Users\Deepak\Envs\dummy\lib\site-packages\django\template\loaders\filesystem.py in get_contents, line 23
with open(origin.name, encoding=self.engine.file_charset)
when i goto admin page then it works but it is not showing output when i try get out put
im thinking
with open(origin.name, encoding=self.engine.file_charset) as fp:
im actually not sure how to fix that, it's beyond of my realm
something tells me it's directory changing
hmm
if they lead to non-existent or wrong path
its common that if people use ..'s after going to a link, they need to do ../..
or .../
well, im not sure how to solve yours but if its something to do with paths, i'd suggest printing out what you're entering in those fields
and look at the results
if they're done correctly or not
the thing is i'm mostly within the flask/quart area, im not entirely sure how django works, but i do know some aspects which is quite similiar between those two
from django.http import HttpResponse
from django.shortcuts import render
def Well(request):
return render(request, '<h1> helloworld </h1>')
``` this is views.py
is that it
?
i mean its enough 
but i really think it can be something to do with paths
kinda like
for example C:\Users\siama\Desktop\GofvenNETAsync\static\image-picker-master\image-picker
if static dissapeared, or maybe the type of document is gone
it wont work
from django.contrib import admin
from django.urls import path , include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('flipkart.urls')),
yeah i found the source
Build a Django Hello World app.
this is where u got it from correct
how does your folder stucture looks like, it could also be that the file you're looking for is in a different directory
v
Hi, In Django DRF, how do we self reference the serializer for a nested Nested relationships ?
ok, found it, it called self referential serializer, the solution was to created minimal seriazer above the existing one and define as field
I am trying to change the theme of my login form in django.
For example, i want it to be seems like this:
https://colorlib.com/etc/lf/Login_v2/index.html
But i can't change how crispy_forms is looking.
And whenever i copy the code, the html works fine. But the form doesn't work because it does not return any value.
How can i solve this?
I don't have my laptop now so i can't show my code. I hope i could explain it.
Any of you use gulp?
Hey guys, anyone uses pytest with Flask?
hello folks!!
m trying to get image as an output. as i have saved image url in database but nothing is happening
even i cant get name of those product which i have saved
from django.http import HttpResponse
from django.shortcuts import render
from .models import Shoes , Electronics
def Well(request):
shoes = Shoes.objects.all()
electronics = Electronics.objects.all()
return render(request, 'home.html', {'allshoes':'shoes',
'allelectronics':'electronics'})
@tight shadow
@tall plaza shouldn't
{'allshoes':'shoes',
'allelectronics':'electronics'}
be
{'allshoes': shoes,
'allelectronics': electronics}
?
Are there any open source static site generators written in flask i could take a look at?
Hi all. I'm about to develop a site for a guy. Used HTML, CSS, PHP, C#, Python before.
He's metal building engineer. Wants to build site where people can customize their building.
Want to build him something like this:
https://www.ezpb.com/design/
What language should I use?
Design your own storage building, shed, barn, cabin, or tiny house. Rent to own, plus FREE delivery & setup. Find an EZ Portable Buildings Dealer near you!
@ancient grove : Maybe js for drawing?
You should look into webassembly
You can run literally any langugae in browser with it
I'm doing this
{{ url_for('static', filename='dragontail-9.12.1/img/champion/splash/{{ player.champion.name }}.jpg') }}
But it doesn't render properly
/static/dragontail-9.12.1/img/champion/splash/%7B%7B%20player.champion.name%20%7D%7D.jpg"
@native tide Check if your file contains any non-english letters
Because it looks like it's the case
Oh I fixed this already
damn, I'm late XD
xd but thanks though
I have a question about using JQuery with Django
I'm completely new to JQ
I have a list of items on my page that's defined by a for x in y method
I'd like each item to have a button that stores information about selected object in localstorage.
I've figured out how to store strings in localstorage but can't figure out how to reach out to the object in db and retrieve its values. Also, said values are not necessarily displayed on the page, like item id for example.
Can someone give me a hand with this one please?
Does jinja have a version of try: except:
no; but you shouldn't have all that logic in the template anyway
Is aiohttp a good choice for an http + ws server?
I'm not used to do asyncio stuff
I get the same exact error as this guy: https://stackoverflow.com/questions/51337758/app-shell-context-processor-decorator-does-not-register-the-function-as-a-shell
I created the following function in a microblog.py file in my ~/Programing/Rasa/myflaskapp/app folder. It creates a shell context that adds a database instance and models to the shell session:
fro...
Nothing seems to work to get it, even the top voted answer (I have both a .flaskenv and a set FLASK_APP=app.py set)
let masteryPoints = document.querySelectorAll('.summoner-mastery');
function one() {
for (points of masteryPoints) {
points.innerText = masteryFormatter(points.innerText);
}
}
function two() {
for (points of masteryPoints) {
points.innerText = points.innerText;
}
}
I have this javascript code
I call one(), it works, but the masteryPoints is changed
so when i call two(), i don't get the desired outcome
how can i fix this
what is two even supposed to do? I'm not good at Javascript but I can't tell what even two does.
It looks like itโs just iterating the same result of what โoneโ returned, which makes it the same
But what I want to do is to use two as a way to get back the initial result before the result got transformed in โoneโ
@wicked tide
Is it not just setting it equal to itself?
I do not understand the actual functional difference between line 11 and say, literally nothing, like what changes in line 11 that does anything?
Yea I know I donโt know how to get it to use masteryPoints variable
It's clear you intend to use it as a global variable, one that doesn't have to passed as an argument, no?
So func one will make adjustments that will be seen if you run two afterwards.
Yea Iโm trying to use as a global so I can use it again to reconvert it back to the original result
Yea
When one is called, it looks like the variable masteryPoints change as well
I want it to be constant
But to convert it back, you would have to write something to transpose it back, points.innerText = points.innerText is just setting that attribute to itself.
Shouldn't you just pass masteryPoints as an argument and let one return it's output? so you still have your original masteryPoints?
points.innerText = points.innerText; I'm guessing here you're guessing that this will somehow change it back? I'm not sure how to break down the logic since I don't know how you're seeing it, but this will just set it to itself.
Yea I understand my logic mistake Iโll try to fix this
Even if I pass it as an argument, global variable changes again
one(masteryPoints);
masteryPoints[0];
>>> <div class="summoner-mastery lvl-6">77.0K</div>
initial masteryPoints[0] is 77002
I am not familiar with how scopes work exactly in Javascript, but I just read this and I'm assuming it's absolute until I test it: Any variable declared outside of a function belongs to the global scope, and is therefore accessible from anywhere in your code.
Meaning that even if you make one accept a variable, it is changing within the global scope and not the function's local scope.
Try changing each (one's and two's argument name), from masteryPoints to anything else you think is suitable, something abstract.
Hmm that's interesting, I'm not too sure what to do from now
Because when I call one, I think it changes the DOM, and when I call the masteryPoints variable again, it calls that element again, it doesn't store the string text within the object as a static variable
if the variable was a string type, then it wouldn't change, but I'm dealing with an object
const masteryPoints = document.querySelectorAll('.summoner-mastery');
Wait, are you returning masteryPoints or setting masteryPoints to the return of one (within the one function)?
I just checked it and even if you had named everything within functions masteryPoints, scope acts like I thought it probably would, which isn't what I said above.
I think this is the issue
const masteryPoints = document.querySelectorAll('.summoner-mastery');
it runs the document.querySelectorAll everytime I call the masteryPoints variable
I can't find a way to store the result as static when called initially
I think the best way is to use store results from the object querySelectorAll to another variable
Hi all. Can someone help me with this? It's really confusing cause I can't see the problem console is pointing out to.
Here's a Jquery code that I have for displaying a table of items based on localStorage.length
var num_values = localStorage.length
var data = {
k: ['#', 'Item', 'Price'],
v: [$.each(num_values , function (index, value) {
'some text',
});]
}
And the error I get in console is
SyntaxError: expected expression, got '}'
it points at line });]
I have checked multiple times if I've forgotten some bracket there or misplaced it.
But as far as I can tell everything is fine with syntax here.
I don't think it's valid to have just 'some text', in the function
at the least it should end in a semicolon rather than a comma
You probably don't need the semicolon after the parenthesis either
var num_values = localStorage.length
var data = {
k: ['#', 'Item', 'Price'],
v: [$.each(num_values , function (index, value) {
['1', '2', '3'],
});]
}
Yeah that's probably it, the semicolon
It shouldn't be there when you're putting it in a list
I am using this example btw:
$('.productDescription').each(function () {
console.log($(this).text());
});
And I tried it without the semicolon as well
Got the same error
like this js var num_values = localStorage.length var data = { k: ['#', 'Item', 'Price'], v: [$.each(num_values , function (index, value) { 'some text'; })] }
Should be good
Yep, already tried it
I tried using data from example which is lain text and it works fine. So it must be that variable and not something else =/
Here's a full example that I'm using
Now I'm trying to replace plain text to my localStorage data
So that it creates a line with key and value for each pair in localStorage
Am I doing it right with that code I brought up earlier?..
@proper hinge ?
No, I don't think so. $.each() doesn't even return anything, does it? It's just meant to be a for loop
But you're trying to do like a list comprehension in Python or something
Just put the each() outside and append to the list
I donรค't even know how you could make use of jquery here
I'm trying to do the analog of for in loop in python
Like with standard javascript you'd use for loop with the localstorage length and then do localstorage.key(index)
Don't see why jquery is useful here
@proper hinge I don't have any experience with JS and jquery actually. Just trying to make sense of it here cause I can't achieve this with pure python
How would you suggest I do this?
Here's an example that goes through all the data in localstorage
Combine that with an array.push https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
and you'll have what you want I think
And I can use it in the same .js file where I already have some jquery scripts?
Hm. I don't see where I should apply Push
In this particular variable I only need to store a list of lists, another function takes that data and converts it into an html table
data.v.push(localstorage.getitem(....)) I believe
Ok 1 sec...
So I tried it with dummy data rn and I seem to be missing something
var data = {
k: ['#', 'Item', 'Price'],
v: [
for(var i =0; i < localStorage.length; i++){
['1', '2', '3'],
}]
}
move the loop outside the object
ok... I don't quite understand the logic I'm supposed to follow here
var data = {
for(var i =0; i < localStorage.length; i++){
['1', '2', '3']
}
k: ['#', 'Item', 'Price'],
v: []
}
Something like that?
var data = {
...
}
for (..) {
data.v.push(...)
}```
var data = {
k: ['#', 'Item', 'Price'],
v: []
}
for(var i =0; i < localStorage.length; i++){
data.v.push(['1', '2', '3']),
}
?
Ok. I see now it works. I thought it's supposed to be a coma because each of those lists has to be separated by commas
That's only a syntactic thing used when you define a list. Not needed when you push
Ok, it almost works
For some reason it won't show key for the first item
Here's the code that I have:
var data = {
k: ['#', 'Item', 'Price'],
v: []
}
for(var i =0; i < localStorage.length; i++){
data.v.push([i, localStorage.getItem(localStorage.key(i)), localStorage.getItem(i)]);
}
Gives me this table:
0 7
1 8 8
2 8 8
@proper hinge
Actually it doesn't show correct keys. I think I got this variable wrong. I need it to show number, key and value in each line
The third one should be just key() rather than getItem(), right?
And keys are strings with names in my case
Ok, that's what I thought too. But how do I get the key itself, not its value?
Isn't that what localStorage.key(i) does?
it returns the value for each key but not the key itself
I've checked in in console log
actually wait a sec...
gonna doublecheck
Storage { 1: "8", 2: "8", 3: "7", length: 3 }
Ok... this is super weird to me
for(var i =0; i < localStorage.length; i++){
data.v.push([i+1, localStorage.getItem(localStorage.key(i)), localStorage.key(i)]);
}
Ah, nvm, I got it. Was misreading it
@proper hinge Can I ask a further question?
So I actually don't want it to show numbers in second row. Instead I'd like to associate them with items in my database via ids. How do I do that? And can I do that in JS?
Does anyone know of a tutorial or other resource on, with SQLAlchemy, allowing dynamic configuration of the model? Like if I want to put a form on the site where a user/admin can add a column to a table?
@frigid egret I think that's a bit beyond me to be honest
Hi! Is it allowed to ask modelling questions here, as in how to optimize my models?
i am developing an API in django + djangorestframework, filled with WW2 info, but im stuck on whether my model inheritance is good.
As you can see, vehicles, airplanes and ships inherit both the WarMachine and Motorized classes, both of which inherit from ManufacturedThing, is this logical and even possible? would'nt you get the attributes two times?
the reason there is a WarMachine class is that you also have non-motorized warmachines, like FLAK88's and stuff
Hi, In my API via DELETE method on one endpoint If I invalidate facebook access token, and token is already invalid, means that I should respond with a 404 error " the requested resource for removal does not exist" or 500 as a response code ?
@tight shadow I wouldn't do a 500. Maybe a 400 or 401.
@inland veldt I see, so the data I am sending is invalid in other words ?
There's no hard rule. I usually save 500 for an unexpected error. In your case you're handling an invalid request, but it's not an error per se.
It's also possible to just return a 200. Depends on the API.
400 sounds like the best thing to do
I agree that 500 is out of the picture here
A 500 would be if you tried to invalidate a valid token and it failed for some reason
Hey guys
import unittest
from app import create_app
import json
class TestApi(unittest.TestCase):
def setUp(self):
self.app = create_app()
def test_create_client(self):
data = {
'username': 'UserTest',
'email': 'Teste123'
}
with self.app.test_client() as client:
result = client.post(
'/api/new/client',
data=data
)
self.assertEqual(result.data, json.dumps(data))
my api is not getting the data
What framework is this?
Flask with unit test
Oh I thought it looked like Falcon so though I could help
Can you describe your issue in more detail?
You say it's not getting data, meaning that when you post data, the api doesn't receive it?
@proper hinge : yea, but i already solved. It was the path, need to be localhost:5000/api and i just put /api/..
Aha, good to know
If anyone is familiar with Flask and how user logins work, if you could help me out with my traceback, that would be wonderful. https://discordapp.com/channels/267624335836053506/303906514266226689/594353083925004288
What's the best payment app to integrate into a website to manage subscription services automatically? I basically need it to be able to email codes to subscribers, stop emailing when their subscription ends, monitor this and be able to add on days globally to subscribers accounts for promotions and cancel reoccurring subscriptions if I do a price change and send an email beforehand to warn about price changes in advanced.
Should I avoid Squarespace if I want to do this?
When I set flask's debug to true when running an app, I always get an error with click saying that No module named cli
@split mirage Probably stripe
I guess I should probably go with Squarespace then. Pricey, but if it gets the job done easily... I was considering Neocities since it's free (it's like Geocities, but revamped and sorta has a social media community aspect to the site to see all the other Neocities pages and stuff) but it's not so straightforward and I don't see anyone else using it as a digital subscription service business page.
can i use flask for real server side programming
Hey, anyone can help me?
My server is not recieving the user data when i run my test
import unittest
from app import create_app
import json
class TestApi(unittest.TestCase):
def setUp(self):
self.app = create_app()
self.api_path = 'localhost:5000/api'
def test_client_index(self):
self.assertEqual(200, self.app.test_client().get().status_code)
def test_create_client(self):
user = {
'username': 'UserTest',
'email': 'Teste123'
}
with self.app.test_client() as client:
result = client.post(
'http://127.0.0.1:5000/api/new/client',
data=user
)
self.assertEqual(result.status_code, 200)
self.assertEqual(result.data, json.dumps(user))
Starting a series as I work on a new service with Falcon, Mongo, and Dart for the front end. Ill be writing blogs as I go on to help people start using this stack. lmk if you have any feedback
Hi, Is my Django SessionMiddleware https://gist.github.com/gnud/3523118c62829eccf3c2baf83600c3a1 properly bypassed for admin cookies ? - So far it works for calling any API endpoint, and sets AnonymousUser at request.user attirbute. My question is whether I have missed some header/cookie just in case. Or if there is a better approach without hacks ?
Do I need to add some special configuration to the django smtp server running on django in docker, or in the docker-compose file? because I've been trying to send an email from a dockerized django app and I get this error on the view: 'gaierror: [Errno -2] Name does not resolve'
@light portal you need to have working smtp server in the docker first
@light portal I for example use Custom mail backend to use Gmail API or mailgun, to workaround server setup with postfix server, if you still want own server probably import the postfix image, not tested
@spiral cedar
Yes flask is a real backend framework and people use it
@tight shadow thanks I'll do that, I knew that docker was small but not like THAT small to not even ship with an email backend
@light portal postfix ๐ฆ is huge
@light portal you can run the postfix as another service in docker-compose, and in your image you can add volume mount for the smtp configuration, just install package for smtp client
i got question about web dev workflow
i am trying to do work as a freelance web dev
but i always make website in Atom
and i upload the work in the client's host
but when my client ask, if it has wordpress
i never used wordpress
how does this work?
@radiant granite Atom the IDE or some library/framework ?
๐
actually i am back
i am still confused ๐ฆ
@tight shadow
so I got a client. I am trying to do web dev work
for my uncle
he wants me to do it in wordpress
i'm not familiar with wordpress. I thought I can do everything in Atom and then upload it on a host
but how do i do this in wordpress??
@radiant granite you install wordpress through some cloud hosting such as Digital ocean, they have premade apps, after it's installed you just install Wordpress plugins and find theme, if you are not familiar with PHP or wordpress development.
or
oh*
but can't i just do my work in Atom IDE and then upload it on Wordpress?
i don't wanna do premade theme
@tight shadow
i have this thing in bootstrap https://jsfiddle.net/juzovwdr/22/
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
if i remove the jquery dependency in the jsfiddle sidebar then it doesnt work
even though i have it in the actual html as a script
any idea why the jquery link in the script isnt working but the jsfiddle jquery is?
@tight shadow alright, I understand, I just want to get smtp working, nothing else
@light portal can you contact me with details when you find a solution, I can use it in a future or post it in my blog :). I already have a solution for smtp client fowarding, (I wil lput your name in the blog post) ?
@radiant granite you want local development, if so you need php enviornent, then the IDE doesn't matter
@tight shadow sure, but I can't promise it will be right away, I'll try to implement the most elegant solution possible, it's for a portfolio project
@radiant granite anotherworkaround is to mount FTP or SSH directory as a normal directory, then open it with Atom,
@light portal no worries, I will revise it and improve it a bit
anyone familiar with quart?
@light portal combine my post http://blog.thedude.tech/2016/04/need-mail-server-tired-of-configuring.html research inside your custom Dockerfile like installing the packages there and mount the volume for config file, then edit the config to point to the service name (like a host name) of the postfix service, this should do
How to configure mail forwarder, using GMAIL as a gateway Opening a security hole visit: https://www.google.com/settings/security/lesss...
@light portal you didn't mentioned if you need mail server for production or just see receive mail ๐ ? If you need fake server https://hub.docker.com/r/mailhog/mailhog/is the right tool for you
@proper hinge http://blog.thedude.tech/2016/04/need-mail-server-tired-of-configuring.html I keep forgetting my domain D:
How to configure mail forwarder, using GMAIL as a gateway Opening a security hole visit: https://www.google.com/settings/security/lesss...
That still won't load for me
HTTPS Availability is being processed. Check back later. Needs time
@proper hinge I m moving toward medium, but I haven't ported most of my posts yet
Well none of the website loads. Not sure what's going on lol
not even the homepage
It times out
"Invalid session" ๐ค
@proper hinge you got dns issues with my domain, try dig @8.8.8.8 blog.thedude.tech
@proper hinge yes, now open kproxy again and paste the url
First time I've had this sort of problem
My knowledge is being blocked by the conspiracy ๐
I've considered starting my own blog though it'd probably be empty
Related is that I went through hell trying to configure postfix on debian
There were several ostensibly good tutorials on it but they were always missing something...
@proper hinge Now days I use Docker for everything, if there is docker toilet image, I would use it, I don't want to waste time configuring. I rather contribute and produce custom images for lots of stuff, so others can enjoy and use; and for me to enjoy someone's work as well.
Well after I configured it I realised I should have put it into a docker image ๐
I resorted to exporting the entire VM from DO when I didn't need it anymore
@proper hinge there is a dedicated image for that, so ๐
I doubt I could avoid having to configure it
postfix,dovecot,dkim,etc
And that other shit that filters out incoming mail
@proper hinge https://github.com/tomav/docker-mailserver good luck hosting it, 1gb Ram just for one service, it easier to pay 20$/mo for a dedicated mail. And plus the responsibility to maintain the dkim stuff when they black list you for no reason, and someone attacks you.
Ok I underestimated what this would include
I did the mailserver thing for fun anyway
I already had to pay $40 cause I needed loads of ram for something else
@proper hinge ๐
Hello, I'm currently learning about "Django", and I would like to know, is it existing website giving free template in HTML5 and CSS3 ? The purpose is to learn how display all of that before go in these two languages.
is there a way to stop the document from scrolling when a modal dialogue is on screen?
@rain dune you can use django templates without writing html or css
Thank you for the info @autumn bobcat
no problem
the nice thing about jinja2 (the language that is used by django for templating) is that it's language-agnostic. You can use it for any kind of text. Someone in this server was talking about using it for automation configs
Hi all again
I have a Jquery function that takes certain variables from Django backend and stores them as an array.
sizeBtn.on('click', function(){
let selBtn = $(this);
let selInfo = [{
'id': selBtn.data('id'),
'name': selBtn.data('name'),
'size': selBtn.data('size'),
'price': selBtn.data('price'),
'quantity': 1}
]
console.log(selInfo)
})
I would like to use some of those values in another function but every time I try to do it, console gives me an error TypeError: selInfo is not a function
And I can't seem to find any information in tutorials. Perhaps I don't know what too google for specifically, I can't be sure.
Can someone help me with this please?
Hello
i am gonna use flask for backend of server ,so what should i know to deploy it on local wifi
i am saying this as i saw some warnings about using flask for production
something related to security and flask is used for development and testing
@native tide
anyway i see that there are many big CO using it so i will use it
How to defend DOS attacks using flask?
same way as anything id imagine
people might be talking about using flasks built in server for that lol
not sure on specifics but i dont think there are glaring security concerns with the framewor itself
hey so will i face any problem in hosting flask app?
maybe if you expose sensitive data to unauthenticated users
the issue is not in using flask for prod, but using the flask server for prod
use the webapp as a wsgi app and put it behind a reverse proxy
in english: uwsgi and nginx
Flask is a web framework. The dev server is a web server
and what i want is to make server script using flask and host it, any problem with this?
No, so long as you use Apache or nginx
what r these things?
Web servers
they r things to host on my own machine right?
Yes
and if i want to host on real server?
Same thing, Apache or nginx
u mean i install them on the server and run using them?
yes
Yeah. You might even have Apache installed by default
and my code remain the same right?
yes
good nice to hear so
you can use flask's dev server for testing and worry about stting up prod web server later
you should follow the tutorial in the docs though
Yeah, it's a pain
ok then one more thing.....
i am making app and server, the app must connect to my server .so i am gonna use ssl certificate to encrypt the channel ,
but i think that my app may be reverse engineered and my server may face something like DOS attack
should i take care of this?
You almost certainly do not have to worry about that
why? is there is something handling this for me?
Take care of it if it happens
It just probably won't happen
I run half a dozen we apps and I have never had an issue
maybe because no hacker wanted to attack
but many hackers are gonna try to hack my system
I can guarantee they won't
Why would they attack you?
to make my server down--> destroy what i am doing
if u mean that no one will care ,so i will have to care as i am sure i will be attacked
Why would they want to attack you
i am working in startup as CTO ,(small startupt)
we will launch service which will harm big companies
so for sure they will try to hack us
thats incredibly illegal
and who can catch them and punishthem?!
like, jail for years, tons of money in damages and fines type illegal
if you host in the US? the us government
they don't screw around with that stuff
the computer fraud and abuse act is super serious here
not in egypt -_-
host in the US and you'll be fine :P
๐ wew
hello why this is not working?
why is what not working?
from flask import Flask,jsonify
from OpenSSL import SSL
#------------
data=[
{"driver":"Mo7sen","dest":str(1)+"km","channel":"133.0.0.3:5050","id":"UI1232"},
{"driver":"Ahmed","dest":str(1)+"km","channel":"155.0.0.3:5050","id":"Issd123"},
{"driver":"7okas","dest":str(2)+"km","channel":"123.1.0.3:5050","id":"UI1xxd6"},
]
#------------
context = SSL.Context(SSL.SSLv23_METHOD)
context.use_privatekey_file('key.key')
context.use_certificate_file('cert.crt')
server=Flask(__name__)
@server.route('/')
def home():
home_page="Uber Clone server __V 1.1__"
return home_page
@server.route('/download')
def download():
page="Download our app from play store"
return page
@server.route('/nearest')
def search():
return jsonify({"drivers":data})
if __name__ == "__main__":
server.run(host='0.0.0.0',port=8080,debug=True,ssl_context=context)
you're better off handling SSL in the reverse proxy
idk what reverse proxy is
@autumn bobcat hey man
res=requests.get("https://192.168.43.23:8080/nearest",verify="cert.crt")
print(res.text)
```what is wrong with this?
dunno, what error are you getting?
// get sidenav state from client storage
let sidenav_open = localStorage.getItem("sidenav");
console.log(sidenav_open); // false
console.log(localStorage.getItem("sidenav")); // false
console.log(sidenav_open); // false
sidenav_open = !sidenav_open;
console.log(sidenav_open); // false
var b = true;
console.log(b); // true
b = !b;
console.log(b); // false
b = !b;
console.log(b); // true
I am a noob, why is sidenav_open always false?
whattttttttttt. ok. it's because it's a string not a boolean
how on earth did that happen
wait localstorage can only be strings? that's super silly
ohhhhh. I have to use json to encode/decode. neat
Pretty much
Just don't store any sensitive information in localstorage and you are good
like tokens etc
i'm getting 403 forbidden from my host running nginx with just a default nginx.conf
the requests are going correctly its just access denied on the index.html
not sure whats going on
just trying to store the state of a sidebar navigation, open/closed ๐
my web dir is owned by nginx:nginx
hmmm
webdev noob - I have a changing sensor reading in python - how do I update that value on the webpage without a refresh?
it seems like I would need to add a javascript element to poll the server?
Hi all
Can someone help me with jQuery?
I have trouble understanding it and can't find the right information with google.
I can try, but I am learning myself so .... have low expectations.
So, I have a list of items on my page. The list has similar objects
And an admin can add or remove those objects
So it can be any number of them
I need to have a button on each of those objects that takes some values and works with them, but only within that specific object.
Using selectors I can make it work but it ends up working with all the objects at the same time
And I can't find any solution to isolate JS to each separate object. All articles I find just tell me that I can use selectors and I can't really have unique selectors in this situation. Not afaik.
oof... yeah. That's above my skill level right now
Can someone please help me with this? I've spent 2 days struggling with this problem.
You can use attributes of the element in the selector which lets you use data aspects. So I would have multiple elements added to my page via templates like data-id="{{income.id}}"> then access that data via var id = trigger.data('id')
@lime thicket can you break it down please? cause I've tried to use data fields previously and it didn't work
Here's my code:
let sizeBtn = $('#selection .btn');
sizeBtn.on('click', function(){
let selBtn = $(this);
let selInfo = [{
'id': selBtn.data('id'),
'name': selBtn.data('name'),
'size': selBtn.data('size'),
'price': selBtn.data('price'),
'quantity': 1}
]
console.log(selInfo)
$(".calculator").data("item-price", selInfo[0].price);
$(".calculator #sel-price").text($(".calculator").data("item-price"));
})
For elements I use a for in loop, so it shows all the elements in DB. And I use data fields to project DB item attributes on to selInfo
Here's my html:
{% for pizza in pizzas %}
<div class="mt-4 mr-4 filterDiv {{ pizza.categories_display }} show">
<div class="card">
<div class="card-body">
<img class="img-thumbnail" src="{{ pizza.photo.url }}" alt="{{ post.name }}">
<h5 class="card-title">{{ pizza.name }} pizza</h5>
<p class="card-text">{{ pizza.description }}</p>
<table class="table" id="selection">
<tbody>
<tr>
<td colspan="2">
<button type="button" class="btn btn-secondary"
data-id="{{ pizza.id }}"
data-name="{{ pizza.name }}"
data-size="small"
data-price="{{ pizza.price_small }}"
data-quantity="1">
Small
</button>
</td>
<td colspan="2">
<button type="button" class="btn btn-secondary"
data-id="{{ pizza.id }}"
data-name="{{ pizza.name }}"
data-size="large"
data-price="{{ pizza.price_large }}">
Large
</button>
</td>
</tr>
<tbody>
<tr class="calculator" pizza-id="{{ pizza.id }}">
<td id="sel-price"></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
what happens when you click the button? and what do you want to happen?
So rn I have 3 pizza objects in my DB. They are all present on the page.
If I press the size button, it's suppose to show price below.
Like that
But it ends up doing it on all the cards, like that:
which is this line $(".calculator #sel-price").text($(".calculator").data("item-price"));
regardless of which button I press, it updates information on all the cards at once
yes
Have you tried getting the element you want to update relative to the button ($(this))
I would assume it's the parent or something along those lines
I am using this argument to address the pressed button. Each button has data values to it, which it takes from DB
You can see it in my html part
I mean instead of using the current selector for updating the text
I don't really know how else I can use it
Seems like right now $(this) represents the button pressed. 1 parent up would be the TD, 2 parents up would be the TR, 3 parents up would be the tbody, 4 parents up would be the table. From here we can walk back down using your selector to grab all tr's with the class calculator within the table
this would only change the text in the one spot
Yes. And I can't figure out how to limit this function to each card separately
So they don't share same data
Can you explain how that would work please?
Instead of the selector $(".calculator #sel-price") you would have a selector that also included the table where the button was pressed. Something along the lines of selTable.find(".calulator #sel-price") Which I believe is the 4th parent of the button but you would have to play with that (there also might be a more eloquent way)
selTable would be defined something like selBtn.parent().parent().parent().parent()
or seems to be some way to get all the parents like selBtn.parents()[3] instead I would guess
Ok, so let selTable = selBtn.parent()[3] finds that specific table next to the button pressed
like that?
let sizeBtn = $('#selection .btn');
sizeBtn.on('click', function(){
let selBtn = $(this);
let selInfo = [{
'id': selBtn.data('id'),
'name': selBtn.data('name'),
'size': selBtn.data('size'),
'price': selBtn.data('price'),
'quantity': 1}
]
console.log(selInfo)
let selTable = selBtn.parent()[3]
selTable.find(".calculator #sel-price").data("item-price", selInfo[0].price);
selTable.find(".calculator #sel-price").text($(".calculator").data("item-price"));
})
you can either stack the .parent() calls or use .parents() and try to access it via an index (I assume that you can)
now it gives me this
TypeError: selTable is undefined
so either
let selTable = selBtn.parent().parent().parent().parent()
or
let selTable = selBtn.parents()[3]
Ok, I've changed it to let selTable = selBtn.parent().parent().parent().parent() but now there's no result
As in, it doesn't do anything
Have you tried playing with this in DevTools? normally I find it way easier to test things. Copy the selector for the button you are working with, make a variable selBtn and start to walk up the DOM via the .parent or .parents call until you get the table
I could go up a level actually since there's a bunch of divs that represent the same object
I don't really know how to do that...
I am familiar with devtools but only in context of html/css
looks like you need to put selTable in $() for the find to work. Like
$(selTable).find(".calculator #sel-price").text(selInfo[0].price);
Still no result.
Also part of the problem is that I don't know how to debug this situation.
If it's an error, it shows that. But if it doesn't do anything, it only frustrates me
If you are in chrome devtools is F12, you can access elements via the console
right click the buttons element in the inspector and hit copy selector
then in the console create selBtn via selBtn = $('<PASTE>')
make sure it worked by doing selBtn.text('TESTING') so you know you are accessing the button
can't find copy selector
I've opened it in chrome
nvm, found it
Ok, I did that
Was it supposed to print TESTING on the button?
Yeah it should have
Didn't do anythning
ok nvm, fixed a typo
But it did that to all the same buttons on all the objects
Since buttons themselves are similar
Did you copy the selector via devtools? because the selector will be specific to a single button
For example when I put your code into a window to play with I get
#selection > tbody:nth-child(1) > tr > td:nth-child(1) > button as the selector
I can then see the text via selBtn.text() and the console outputs "Small"
I can set it to TEST via selBtn.text('TEST')
Ok, so selector on those buttons is the same because the difference between those objects is in data fields
Does it replace text only for one button?
From this line I can see it found 3 similar objects when I applied the change
If that is the case do selBtn = selBtn[0] afterwards
get the first element in the 3
Point is, try and play around in DevTools till you get your JS working, where you can modify the right element by hand
then add it back in your code
Ok, thanks. I will try to.
anyone familiar with quart know how to redirect from one blueprint to another, sadly its being fucking stupid and the many ways i have tried don't work, sadly from what i have seen its undocumented and flasks(because of quart being asyncio flask basically) docs also didn't help got it working
Hi guys, I am trying to implement Ariadne to my django app. I got problem with pagination. Well i am using django's default pagination. Thing is i want to select after certain objects in paginated queryset. Here is my resolver. So there is an after argument which would be optional but when provided i have to fetch from paginated queryset right after it's value. In this case after="some-UUID"
def resolve_artist_releases(artist, *_, single=None, first=10, skip=1, after=None, last=None):
albums = artist.album_set.all() if single is None else artist.album_set.filter(single=single)
p = Paginator(albums.order_by("-created_dt"), first)
if last:
p = Paginator(albums.order_by("created_dt"), last)
return p.page(skip).object_list
Can you guys help me on this?
Hey guys! Does โpostโ request need to return anything?
Maybe sometimes itโll return render_template or redirect. But what else?
In Flask
And usually how do we handle unsuccessful login? For example, thereโs a post request to the server, and it finds password unmatched. In theory, weโd want the server to pass/return maybe a code โ000โ to stand for โinvalid username or passwordโ. But I donโt think we can do this under post request.
What I did was I had a post request followed by a get request. So after the front end posted, the server checked if the strings passed to it matched with the ones in the database and updated the accountโs status in database; then, there was a get request to access the database to get the status.
It seems working. But is this the right/effective way to do this?
Every view needs to return something
Instead of returning a magic number, you show return a json string with the error info
You should ideally just return the result of the post request saves an unnecessary additional request
Hey Djangonauts, is it possible to select next objects from paginated objects by id? like, select all after certain id of objects ?
paginated = Paginator(Blog.objects.all(), 10) like for this case i want to select all after id=5 blogposts eg(6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
@stiff totem Can you provide your code please?
I;m new to jQuery but I can at least look at what you have
He's offline... oh well
I have a question, guys
I have some data fields on my page. And depending on user input they can change. I have a button that I'd like to store those data values in an array in localStorage.
Here's a part of code that I thought might work:
if (Btn.is(".add-cart")){
localStorage.content = {
'id': data.id,
'name': data.name,
'size': data.size,
'quantity': data.quantity,
'price': calculatorPrice,
}
But for some reason local storage ends up having this:
Storage
โ content: "[object Object]"
โ length: 1
โ <entries>
โโ 0: content โ "[object Object]"
<key>: "content"
<value>: "[object Object]"
That's what console log shows me.
Can someone please help me with that?
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings).
@frigid egret ^ you'll need to serialize and deserialize your data to store objects in localStorage
unless you didn't intend for everything to end up as a single object called content
in the latter case the 1:1 answer that will convert your current code into what you wanted would be:
if (Btn.is(".add-cart")){
localStorage.setItem('id'data.id);
localStorage.setItem('name', data.name);
localStorage.setItem('size', data.size);
localStorage.setItem('quantity', data.quantity);
localStorage.setItem('price', calculatorPrice);
}```
Oh, I had to clarify
I want to add those arrays one buy one and not replace them in case user presses the button multiple times
err, actually it's been a minute since I used localstorage, it's .setItem() not using the accessor []
ok... so to further clarify.
I would like to store those arrays and be able to show them on a different page (in a table) of the website. That's why I thought localstorage is necessary
Storing it server-side may be easier and/or more secure, and is probably recommended unless you have bandwidth/speed/responsiveness/caching constraints
or want to limit server resource usage as much as physically possible
This data is not sensitive
So I don't see a problem in storing it in localStorage
So, can you please explain how to store multiple arrays in localStorage?
You need to serialize the arrays. There are many ways to do that. The most common/simple for this is most likely to use the JSON.stringify()ย and JSON.parse() methods: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
"serialize" the arrays here means transforming the arrays into basic strings that follow a predetermined encoding pattern of your choice, so that they can then be "parsed" and "deserialized", meaning some other bit of code will read that string and recognize the formatting and create the right object data out of it
Hello, I'm using flask and flask_wtf, can anyone guide me on what would be the correct approach to have a StringField that works as an array?
Ok, apparently this works in a different manner than in other languages, and instead of using the same name for all the inputs its adding a -i to it, fair enough
Hello guys
What I want is after I cloned a project from a source in github it has 2 branches master and user-auth
How do I merge user-auth to the master branch so that I can get the most updated codebase
Fork it and merge the branches?
hello i want to make uber-like app back end in flask
for the real time connection i am using socketio
my question is how to make the connection and event triggers be between client and server only? i mean to able clients to communicate with the server only not another client
Are the django rest framework docs terrible or is it just me? I think a ViewSet may be right for me but I don't see how to link a given request to a list, create, retrieve, etc method or if that's automatically done. Also, I don't see where the format of the URL is ahead of registering it with the Router.
Ok, I see it now. It's in the router page.
Yeah, django can be overwhelming with all of it's options but flask is too barebones. The packages are too disjointed and it all feels cobbled together.
Hi all. With flask if I have multiple routes sat the same location (example: /results) but different function names how do I call the right one? I know I need JS but not sure where to start. On mobile so no code at the moment. Thanks
I do have them broken up by blueprints though if it helps
Anyone ever tried to host multiple Django sites on Apache? I can get either to run but only alone. Using mod_wsgi... Also are there any alternatives to hosting Django on windows without using either Apache or IIS?
Okay lol so how do I link mongodb atlas and django?
I'm using mongoengine
But the only host it's connecting to is localhost:27017 even though I'm specifying connect(host='mongo+srv://secretstuff')
Is there any other way I can hook mongodb with django? Or am I missing something up? Or am I just going to have to stick with having my database code in my views?
bump
''' hello '''
'''python hello '''
import findmax #findmax.py
n = ["1", "2"]
print(findmax.find_max(n))
sorry
Anybody good with Django?
I need advise
I need advise on project ideas related to Data like Big Data with Spark or DevOps + Data stuff
related to Django
i'm using a bit of Vue in django templates. Just some simple stuff, nothing fancy. I'm not an expert in js... far from it. If I stick to ES5 stuff, should I worry about transpiling and polyfiling? I have no intentions to support very old browsers.
you'll be fine, always depends on the context
How to test ariadne resolvers?with Django
Hello, I'm working on Django and I'have an issue. I try to keep a value in a box once selected, but it doesn't work. It's like my if statement doesn't work :/
There is the script :
<label class="sr-only">State</label>
<select name="state" class="form-control">
<option selected="true" disabled="disabled">State (All)</option>
{% for key, value in state_choices.items %}
{% if key == value %}
<option value="{{ key }}" selected>{{ value }}</option>
{% else %}
<option value="{{ key }}">{{ value }}</option>
{% endif %}
{% endfor %}
</select>
</div>```
<option value="{{ key }}" selected>{{ value }}</option>```
I can see all the values in the combobox, then I'm sure that is not coming from the variables :/
Okay, I found it. That was coming from my view file
Im having issues aligning an image in the left 75% of the screen with CSS/HTML
Anyone have any thoughts on the new Flask 1.1 release?
any new key reworks?
loss of python 3.4
Returning dictionaries from views makes them auto-json
"URL matching now occurs after the request context is pushed, rather than when it's created. This allows custom URL converters to access the app and request contexts, such as to query a database for an id. :issue:3088"
i do not understand the __ name __ part in flask
like what does name mean to main and how won't it work if i am importing
i am following up corey schafer's tutorial
Can someone fix this Django doesn't refresh my static files
I have tried to clear the static and the problem is unchanged
What did you do? I'm encountering the same issue actually
You should clear the static files by
python manage.py collectstatic --noinput --clear
and you should define a STATIC_ROOT & STATICFILES_DIR in your setting following https://docs.djangoproject.com/en/2.2/howto/static-files/
and dont forget to collect static by py manage.py collectstatic
Dont forget to delete your browser cashe
Hope it solve your problem
@lucid salmon
If the problem still occurs , Dm
I want to update a page without refreshing it, so I use ajax and update .innerHTML. Problem is I also need to execute some JavaScript, but that JS relies an object passed to the template. Per the standard, <script> tags won't execute when .innerHTML is updated.
I could just respond with JSON instead and construct all the elements in JS but that just feels clunky. I could also include the rendered HTML in JSON, but sounds like escaping stuff will be problematic and the idea is generally off-putting. I could separate it into two requests, but that seems redundant. I could do some hacky shit with DOMParser and re-creating the <script> element but that has escape issues and... it's hacky.
What's a good way to approach this problem?
Thanks @late gale
Yeah ๐
๐ฌ
@proper hinge respond with JSON and create the elements doesn't seem clunky to me; Lots of frameworks do it this way, it can actually be faster than updating innerHTML. When including html in a json object, the escaping should be automatic; you shouldn't have to do anything regarding escaping yourself.
So you can just return a json with the javascript and the html in two separate json elements, then add them to the page
I just prefer to use templates over JS where possible
Right now I went with HTML5 data attributes
The context is I am rendering a graph with a js lib and I needed access to the data for x and y
Hey folks
Hello
I'm having some issues with compiling my sass files in flask
I'm using flask_assets and libsass
erm- how do I post code blocks in disco?
'assets/custom.sass',
filters='libsass',
output='static/assets/css/main.css'
)```
aha!
my custom.sass has all of my imports at the bottom, but they don't seem to update when I refresh the server or clear the cache in chrome
i do not understand why "title" in the if statement did not have {{ }} but in the other place it had it..
Okay
Got it ?
Yeah it is from the developers of flask
like a rule in flask
i can't say why strings need quotes, because it is a rule, same with this example
Glad I helped ๐
the two brackets {{ }} essentially say "output this variable as a string inside the templating code"
because you're in a statement ({% %}) you don't need that (don't even think you can do that), because you're comparing the actual value of the variable, not outputting as a string
thanks guys โค @late gale @autumn bobcat
No problem @native tide ๐
I have uploaded images using html and css on a django project but I wanted to update it from admin page but the question is. Is the photo uploaded by admin has the same style of css otherwise how to give it a style
Please answer me fast
It depends if you give it some style or assign it a class with some style
Is it better to use a standard common used login system for Flask projects, or making my own one?
I would say use flask_login
Reinventing the wheel isnt really necessary and will take up 80% of your project
@late gale it will have the same styling like everyone other uploaded it
Thank you @vagrant adder
I have solved it but why does my image appear like this
It is uploaded from the admin page
It's from admin page not an image from a certain folder
or should I connect it to a specific folder ?
First save it, then link it
I don't want to save it so i can upload it from other places
What i am trying to say is whenever I upload an image from admin page , it be uploaded in the page without save it in a certain directory so If i want to upload an image from my phone , I can do it easily.. Understood?
What do you mean by upload to the page but without saving it?
Like you post an image on facebook then delete it but it still posted. so if i delete my image it still be on my page
You should make a storage for your photos somewhere on cloud(e.g. dropbox)
So if you delete it on page, it is still on dropbox for you to see it
Why should i have dropbox when i can see it from my website
So you want to see your photo even after deleting it?
Or you want to delete it completely
Like it be saved on database
And you can see it even after you deleted it from site?
I have a blog page which i can post any post from my admin and it be updated on its page and I can delete it from the admin page
I have downloaded an image then I uploaded it on admin page then it have uploaded on the projects page now I dont want the image cause it's already stored in my website so when i delete my image on my computer it still be on website
Ooh
Understood?
So you want to have your images always but not stored on your pc
yup
So
Theres this thing called cloud storage
Essentially its a big hard disk accessible from anywhere
dropbox,google drive, aws s3 bucket...
I would recommend saving pics on a cloud storage solution
You still didn't understand
I want to upload the image on the website server that i can upload it from admin page and it be uploaded without save it anywhere
It be on database of Django like my blog posts
Well, for data to show up it needs to be saved somewhere
Database is justa bunch of data saved and sorted
then why my blog posts not saved and can be posted from the admin page

