#web-development
2 messages · Page 171 of 1
are you only using nginx for mysql?
postgresql
why not install postgresql via the installers on the website and use the Psycopg2 python package to use it in flask
you could use the first part of this tutorial to install it https://realpython.com/flask-by-example-part-2-postgres-sqlalchemy-and-alembic/
use this only for development tho
linux will always be better for deployment for security risks and stability
save the files on your server system and just add the file path to the database
what do you mean?
create a directory and save the files to that directory. then create a route to serve the files from that directory, you can specify this, lets say this path is /files, you'd define it so that it accepts dynamic values: /files/<file_name> etc. then when you save on your db, you'd save as something like filepath = "/files/file_name"
Hello there , simple question what is the point of cookies in website?
i wrote this to serve images
Any recommendations on how to implement real-time chat into my web app?
React+Django+GraphQL stack
i think you should use something like ajax(maybe)
in simple terms, to remember stuff
oh! so i must use it in my website yeh ?
ok you mean in "remember stuff" like username or password or can save any thing else ?
yeah, you don't want to save sensitive data like that in a cookie
like, you can use them to remember items someone saved in a cart or just basic info. I think they are mostly used for session management etc (when you want to authenticate a user etc)
what i am saying is not the full story, so it's best you do your research
in addition to cookies, there's also JWTs, and localstorage i believe
thanks a lot ❤
I heard term web-sockets/channels about it (never tried)
oh, remembered another word = it requires async perhaps
anyway, web-sockets should support real time thing to make
in theory
Hmm, yea that's a whole mess if I get into that. Maybe just an email-like messaging for now would work.
Is there a way to push notifications/messages to a client without websockets when they happen?
Channels doesn't seem to have taken off too well so I'm not so sure about using them.
the most simplistic solution should be just... making in timer requests to API end point in order to find new messages.
So just polling every X seconds if they sit on the chat page.
not really optimized solution, but hay, still a solution.
yeah
just make some way to pause/quit chat page if they aren't active
what does sphinx class as a homepage url pattern?
Why don't I get CSP violations when I run my Flask site locally? It's annoying to have to redeploy every time to see if I fixed my policy.
Locally, your server and your request may be on the same origin
But it's requesting resources from other domains
Lol! Sounds like you made it through
I send myself a zip file of a website(blog site) to myself but for sum reason I can't seem to run it
I've hit a bit of a wall with a Django error. Question on Stack Overflow here: https://stackoverflow.com/questions/68306715/in-django-3-2-i-am-getting-this-error-app-importerror-module-apps-articles-d
@app.route("/admin", methods = ["POST", "GET"])
@login_required
def admin():
usr = None
form = UpdateForm()
if current_user.userType == "admin":
if request.method == "POST":
usr = User.query.filter_by(username = request.form["admin"]).all()
print(request.form["admin"])
for i in usr:
form.username.data = i.username
form.theClass.data = i.theClass
form.userType = i.userType
elif form.validate_on_submit():
print("valid now")
updateUsr = User.query.filter_by(id =
request.form.get("getId"))
updateUsr.username = form.username.data
updateUsr.theClass = form.theClass.data
db.session.commit()
flash("data updated", "info")
return render_template("admin.html", result = usr, form = form)```
i am trying to update the values but it doesnt work.
i get a big csrf token at get request. can anyone help
?
Just in case question: Does your template have the csrf token tag?
so with sphinx,
<nav class="bd-links" id="bd-docs-nav" aria-label="{{ _('Main navigation') }}">
<div class="bd-toc-item active">
{{ generate_nav_html("sidebar",
maxdepth=theme_navigation_depth|int,
collapse=theme_collapse_navigation|tobool,
includehidden=True,
titles_only=True) }}
</div>
</nav>
This will generate a toctree on said page, but how can i choose what to add to it?
nvm my bad
i just modified some thing slightly
basically i want to make this model so one owner can have multiple structures and a structure refers only to one owner. The problem is that the foreign key of the structure is not getting the id of the owner which is wrong, because it should refers to it
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
is_customer = models.BooleanField(default=False)
is_owner = models.BooleanField(default=False)
class Customer(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True)
short_bio = models.CharField(max_length=255)
class Structure(models.Model):
structure_name = models.CharField(max_length=255)
avaiable_rooms = models.IntegerField()
price = models.FloatField()
owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
I undertand but I not have bad intentions, just, that site is a little intesable and the get new products I need chek manually every time, then I just want, when the site is accesible, check automatically for new items... and get some notification... just that...
and I dont want break the captcha, I want solve it manually with my real user... normally like a browser
late reply, sorry. And ehh, I'll just use a model. I don't think I'll have other admins to my site but meh
now I just need to figure out how to structure it
for only one text field entry
okay, maybe not actually
might need a color option to it
i understand, but sites with captchas are pretty hard to get around. the latest captcha doesn't return an error you can catch, and locks all other parts of the site
if you really need this data, then the site should have a REST API for passing data between front and backend
or maybe one that is meant for public consumption
If you want to manually do the captcha, you can use selenium as it'll open a browser instance which you can interact with. (plus it can automatically scrape the data once you've verified the captcha). apart from that, there's some captcha services out there but they're paid. cheap though.
Hello need help returning a variable:
this is my code:
@app.route("/login", methods=['GET', 'POST'])
def login():
takeName = "somethingsomething"
if takeName == "somethingsomething":
return redirect(url_for('menu', takeName)) #want to return takeName to use inside of menu() function
@app.route("/menu", methods=['GET', 'POST'])
def menu(takeName):
print(menu(takeName))
But im getting the following error
TypeError: menu() missing 1 required positional argument: 'takeName'
Idk what to do
hi, i'm attempting to deploy my flask app to linode. it works locally, but when i deploy to linode and try to access the webapp, my apache logs show: https://paste.pythondiscord.com/pokevedoxe.yaml
here is my webapp.wsgi:
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/webApp/")
from zealbot.main import app as application
application.secret_key = 'asdfjkl;'
and here is my main.py: https://paste.pythondiscord.com/cukomewuhe.py
and here is my folder structure on the linode server. anyone available to help? i'm not sure why it's not recognizing the module - it's clearly there
hy, was stuck in a simple django issue, wondering if anyone here can help
hmm, bot for some reason prevents me to share the link.
You need to pass it to pass "takeName" as a path parameter, all you need do to is the below.
@app.route("/login", methods=['GET', 'POST'])
def login():
takeName = "somethingsomething"
if takeName == "somethingsomething":
return redirect(url_for('menu', takeName=takeName)) #want to return takeName to use inside of menu() function
@app.route("/menu/<takeName>", methods=['GET', 'POST'])
def menu(takeName):
print(menu(takeName))
@inland oak we filter that link because people tend to drop it without explanation to people looking for help, which we consider somewhat rude
so, if I 'll give description, it would be ok?
i mean it'll still get filtered
but in general the content of the webpage is good, it's just the way the link is used that can be unhelpful
dontasktoask dot com
this link could be provided as a new rule: don't ask to ask, just ask
perfectly explaining why they are asking their questions in a wrong way
it's covered in #❓|how-to-get-help
it will work too 😉
https://pythondiscord.com/pages/guides/pydis-guides/asking-good-questions/#q-can-i-ask-a-question as answer
A guide for how to ask good questions in our community.
@summer cairn Hey, modularize your zealbot folder by adding a __init__.py file into it, and you should be okay.
fixed it
im starting out on html lol
need help
whats the size for an custom bullet in an ul
Do I create another app in my project for other features of my site that I'd like to have? I don't have a models.py
hello
i was just reading a simple tutorial for flask
and there was this function-:
def gfg():
return 'geeksforgeeks'
app.add_url_rule('/', 'g2g', gfg)
i dont understand what the second argument(endpoint) in this does, as its not explained and changing it doesnt effect the webpage either
app is just a flask.Flask object btw
It map's the name "g2g" with the path "/"
by default, if you don't provide the second parameter, it takes the name of the view function, which is "gfg" and maps it to "/"
you can ignore the second parameter for now, if your early on your web dev journey
and @quaint dew ,
@app.route("/")
def gfg():
return "geeksforgeeks"
is far more easier
Np.
Guys, I am a front-end dev and recently my boss told me to build a django project
Any learning advices?
I used to use cpp in school and I have learned how to use python
but never done things related to backend
u may visit some youtube tutorials and familiarize urself about django
if want i can also help you
feel free to DM me for any help
Hi, this is django/python question.. Can I ask:
- Why we need to add *args, kwargs everytime we init? where will this args and kwargs be passing from?
- Why we need to super(<the same form>...) when we init?
class BillForm(forms.Form):
pass
def __init__(self, *args, **kwargs):
super(BillForm, self).__init__(*args, **kwargs)
in general we dont' need both.
but I can see you are inhering from Form.
If you are going to add your own code in init, you need doing those actions in order to not override already existing init.
I can guess that if you aren't needing any logic in init, just don't define init at all. It would be inheritered from Form already.
basically, do this init/super/args/kwargs only if you are going to add some code logic besides this one line, otherwise don't re-define init at all
(never touched those forms, but this is a logical python... logic I can guess)
okayy, meaning if i add something to the init part and NOT call for super, the form wont show the other stuffs except the newly added part?
if you will redefine init and not call super, it will just get broken highly possibly
it depends on what it has in its internal code
follow inside the library and read
what happens in its init
right, okay thanks a lot @inland oak !!
hi, thanks for following up. i actually have __ init __.py within the next level down in the structure. here's my init file contents: https://paste.pythondiscord.com/qasilejeqa.py -- should i just change the name of my main.py to init and init to main?
here is my init in my current folder structure
using python, how do i prevent people from going to specific urls before logging in?
am using builtin authentication form
class login_form(AuthenticationForm):
pass
def login_view(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username = username, password = password)
if user:
login(request,user)
form = login_form()
return render(request,'mainapp/login.html',{'form':form})```
is this a right way to login?
i didnt worked with authentication before but its something like this https://docs.djangoproject.com/en/3.2/topics/auth/default/#the-permission-required-decorator
im using flask
sorry then idk anything about flask
you could make a decorator to check whether someone is authenticated. if they are not you can redirect them elsewhere
hey, anyone know how to config flask-session with sqlalchemy, I cannot find any solution and the docs are not the best and no real examples
https://www.youtube.com/watch?v=dam0GPOAvVI << step by step youtube on how to do this
Heyo so
is it possible to run raw sql code in this django-python shell?
in this case ```SELECT * FROM User
thank you so much !
cuz this django queries are rather inconvenient
anyway there is no Flask-Session package used
I have not got problem with the database itself and the models or other stuff only this and the config of it
ah i see, my bad
For flask, you can use an extension called Flask-Login for such authentication issues and others. Go check out the docs for info on how to use it- https://flask-login.readthedocs.io/en/latest/
Alternatively, you can use Miguel grinberg's flask mega-tutorial Chapter 5 to learn how to use Flask-Login
use loginrequired mixin...
Hello Everyone!!
I'm developing an Automated Time Tabling System application with Django
After randomizing the courses provided by the schools admin on the table, how do I work with constraints (like carryover courses) for the courses on the table to prevent clashing?
hey uhh anyone here familiar with flask and sqlalchemy
anyway
@app.route('/user',methods=["GET","POST"])
def user():
def get_data():
formi=Userform()
if formi.is_submitted():
student=Students(fullname=formi.fullname,personal_email=formi.personal_email,dialling_num=formi.dialling_num,branch=formi.branch,ocupation=formi.occupation)
db.session.add(student)
db.session.commit()
return render_template("User/edit_page.html",form=formi)
x=Students.query.filter_by(fullname=???)
return render_template("User/Homepage.html")
im strugglin on the place where i put ???
i want to assign it to the logged in user so it can display his own info to him
im having a hard time understanding sessions
What is '???'
You have to pass the object for the logged in user to the render_template so you can use it in the template
that loggin thing that im struggling with
meanwhile i went to work on something else and
@app.route('/user',methods=["GET","POST"])
def user():
return render_template("User/Homepage.html")
def get_data():
formi=Userform()
if formi.is_submitted():
student=Students(fullname=formi.fullname,personal_email=formi.personal_email,dialling_num=formi.dialling_num,branch=formi.branch,ocupation=formi.occupation)
db.session.add(student)
db.session.commit()
return render_template("User/edit_page.html",form=formi)
``` i made to view functions that share the same route
```html
{% extends "Layout_user.html" %}
{% block content %}
<section class="content">
<h2 id="welcome">Welcome to your Dashboard</h2>
<div class="info">
<div class="userinfo">
<img src="{{ url_for('static',filename='img/imageblank.png') }}" alt="profilepic">
<a href="{{ url_for('get_data')}}"></a>
</div>
</div>
</section>
{% endblock %}
and gaved the <a> the get_data function so when i click it triggeres that function
and im getting this error
werkzeug.routing.BuildError
werkzeug.routing.BuildError: Could not build url for endpoint 'get_data'. Did you mean 'static' instead?
how can I implement this in my html file?
<script src="https://cdn.jsdelivr.net/gh/joeymalvinni/webrtc-ip/dist/bundle.dev.js"></script>
<script>
getIPs().then(res => document.write(res.join('\n')))
</script>```
Hey guys,
I have a VPS (on OVH) that has a file based database in it (sqlite).
And I want to make an API to query a specific resource from the db.
The API will be used by a shopify app.
I have so far developed the API using Quart with python.
My question is:
How can I expose the API to the public and secure it ?
Use api keys
Store all api keys as a table in ur db
Each key can have permissions for each user
Then check for an api key in the header of a request
And bing bang bong you got an auth system
Django question: I have 2 model classes inside of an app models.py. In my admin panel I would like to take a model from one of the class and two from the other and display them and allow filtering. I am not sure how to combine them together to allow this.
do u mean display two different model classes together in same page?
for eg if this is my code:
from flask import Flask
import socket
app = Flask(__name__)
@app.route('/')
def test_site():
return 'This is a test website.'
if __name__ == '__main__':
ip = socket.gethostbyname(socket.gethostname())
app.run(host=ip) #host_type='global'?
then how do i convert it to be hosted globally
putting in my public IPaddress doesn't work
anyone knows?
Unless its changed in last few years the built in wsgi server is only suitable for debugging only. Ignoring this you can host it on all interfaces and not just the loop back address you should be able to bind it to all interfaces by using 0.0.0.0
putting the ip as '0.0.0.0' starts hosting the server on my private ip
which makes it a localhost
i'm testing your code now
Changing the last line
app.run(host="0.0.0.0")
$ python flask_example.py
127.0.1.1
* Serving Flask app 'flask_example' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://192.168.1.37:5000/ (Press CTRL+C to quit)
192.168.1.39 - - [10/Jul/2021 16:48:19] "GET / HTTP/1.1" 200 -
And .39 is the IP from from phone.
So it worked as I would expect.
you are able to connect from a different network?
No as its a private IP address range behind a NAT. You might be able to do port forwarding from your router to make it public. Though its not wise with debug mode.
What about exposing? That's my biggest problem now
normally this is how i did directly getting from APi response ```js
function createCharts(data) {
let dailyTemps = data.openweathermap.daily.map((e) => e.temp);
new ApexCharts(document.querySelector("#chart"), {
series: [
{
name: "High",
data: dailyTemps.map((e) => e.max)
},
],
chart: {
height: 386,
width: "100%",
type: "bar",
toolbar: {
show: true
}
},
colors: ["#008ffb", "#00e396"],
dataLabels: {
enabled: false
},
stroke: {
curve: "smooth"
},
markers: {
size: 1
},
xaxis: {
categories: openweather_day,
title: {
text: "Temperature",
}
},
yaxis: {
labels: {
formatter: function (value) {
return value;
}
},
},
legend: {
position: "bottom",
horizontalAlign: "right",
floating: true,
offsetY: 5,
offsetX: -5
}
}).render();
}``` what should be changed here if we want to get data from data.json file instead pf direcly from api because i stored my api response nycreating a data.json file
You should not be making 2 view functions with the same route. In this case, all the code can be put in only one function. Put the last template (homepage) below all the other code but outside the if statement
hey !, Just add a "__init__.py" file in zealbot folder, or yeah, you can just rename main.py to "__init__.py" @summer cairn
Hey guys,
Suppose I have a very minimalist API on my local machine.
How do I expose it to the world ?
Hi, How do i use flask-sqlalchemy queries with a Huey worker of a Flask App ?
from engine.models import Languages
from app.extensions import db
from app import create_huey_app
from app.queue import create_huey
huey = create_huey()
@huey.task()
def perform_analysis(text:str):
app = create_huey_app()
with app.app_context():
db.create_all()
print(db.session)
print(db.session.query(Languages)) #OUTPUT : None
print(Languages.query.all()) #OUTPUT : None
print(db.session.query(Languages).all()) #OUTPUT : None
Output
<sqlalchemy.orm.scoping.scoped_session object at 0x000001FABDA30748>
Same goes with
db.session.add(new_entry)
db.session.commit()
I checked and these queries do work when I am using them directly from a view/route function like this
@blueprint.route('/')
def route_default():
db.create_all()
print(db.session) #<sqlalchemy.orm.scoping.scoped_session object at 0x000001FABDA30748>
print(db.session.query(Languages)) #[Java,CSS,Python]
perform_analysis('test') #No query response using this
return "Success"
What is expected ?
database queries to return results
class Admin(db.Model):
id=db.Column(db.Integer(),primary_key=True)
fullname=db.Column(db.String(50),unique=True,nullable=False)
email=db.Column(db.String,unique=True,nullable=False)
password=db.Column(db.String(),unique=True,nullable=False)
def __repr__(self):
return f'Admin:{Admin.id} {Admin.fullname} {Admin.dialling_num} {Admin.branch}'
class Students(Admin):
personal_email=db.Column(db.String,unique=True,nullable=False)
dialling_num=db.Column(db.String(),unique=True)
branch=db.Column(db.String())
occupation=db.Column(db.String())
def __repr__(self):
return f'Student:{Students.id} {Students.fullname} {Students.dialling_num} {Students.branch}'
``` something like this should work
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: admin.personal_email
[SQL: SELECT admin.id AS admin_id, admin.fullname AS admin_fullname, admin.email AS admin_email, admin.password AS admin_password, admin.personal_email AS admin_personal_email, admin.dialling_num AS admin_dialling_num, admin.branch AS admin_branch, admin.occupation AS admin_occupation
FROM admin
WHERE admin.email = ? AND admin.password = ?
LIMIT ? OFFSET ?]
[parameters: ('elmamouni@ecolewa.com', 'Amineamine', 1, 0)]
(Background on this error at: http://sqlalche.me/e/14/e3q8)
@native tide You could host it on a hosting platform, i use Heroku to host all my flask web apps.
I can't, and here's why.
I have a db that's already in a remote desktop.
I made the api so that external apps can use it to access a resource in that db ( which is file based)
And I don't want to migrate the DB unless I REALLY have to
Oh, Okay.
So is there another way ?
There are, but i don't know them well enough. : (
Shoot and I'll try to do some research
i was reading the documentation and i wanna know if it's possible to load the user based on other stuff ( email or something ...)
Can I learn Python, html, css and js at the same time? I want to be a full stack dev
well noo even if you can you'll just burnout unless if you can clone yourself 5 times then yeah sure
Thanks for the information sir ,but how can someone be a full stack. I know it's hard😂
well firstly to kinda get you feet wet i recommend you to start with some html css and js
js is vast and please please go with the basics don't jump on a framework or something learn to do plain js until u feel u get a grasp of what you're doing then learn some python php node.js idk you pick which syntax and pl you wanna deal with and yeah
also learn some networking stuff how http works ip tcp and other stuff
Thank you so much for the tips! Much appreciated bro❤️
sure, why not 😉
you can start with just python + html + css
and then add js to this mix
backend is a deephole though, and frontend is not that small too
Guys me has a question
Should I invest my time to learn Django only
Like become a expert in it only
as opposed to?
Is it worth full and will it get me a good job online
well
it depends on where you are
but
there are defo places you can get a job by being good @ Django
No that's the thing I want a online job so my location does not matter
it does.
because even for remote jobs
In my country using technology is like a taboo
there are many companies which care about timezone
True....
...
Anyways let's ignore that
Here
Should I learn Django
Or something else
Like game dev
In C++/C# or something like that
Or learn data analysis
See me has had one interest always and that is technology and coding
Python gave me that
Now me is finding one skill to specialise in python
So I need to find one thing that is extremely worth it
And does not need math like machine learning
any good yt tut or anything , so i can learn to make cart system and cookies for my site
what is this country out of curiosity
i heard only about north corea like that
any good yt tut or anything , so i can learn to make cart system and cookies for my site
@inland oak

Rather not tell because of privacy
i want to be good in django now
u can tell country he isnt asking ur city

@dusk portal just search it up on YouTube and find one
well, suit yourself
many are trash they r 2018-2019 using
and idk
ajax
Well you won't find one that was made yesterday
Learn also need modification
Learn the 2019 format
Read the doc
And recreate a new one with your own imagination and hard work
Read the doc for the new 2021 one*
When linking things in flask, do i have to use the url_for function? I found that just stating the app route function name works.
what do you mean by "when linking things"?
href="{{url_for('index')}}" vs href=index
exposing to the public you mean?
you're saying the second option works?
yep
let me try it
I did it for my website. Now im working on a blog following codemy and they are using url_for. Didnt know if it made a different.
It even works for longer paths. So like on my website, youll go to ...com/rps/paper and itll take you back to ...com/
i refactored it a little bit
@app.route('/',methods=["GET","POST"])
def login():
if current_user.is_authenticated:
if Admin:
return redirect(url_for('admin'))
elif Students:
return redirect(url_for('user'))
form=Login_formcall()
if form.is_submitted():
if form.email_user.data.split('@')[1]=="direwa.com":
if Admin.query.filter_by(email=form.email_user.data,password=form.password.data).first():
# global y
# y=Admin.query.get(form.email_user.data)
login_user(Admin())
return redirect(url_for('admin'))
else:
flash("you don't exist")
elif form.email_user.data.split('@')[1]=="ecolewa.com":
if Students.query.filter_by(email=form.email_user.data,password=form.password.data).first():
# global x
# x=Students.query.get(form.email_user.data)
login_user(Students())
return redirect(url_for('user'))
else:
flash("the User doesn't exist")
return render_template("Layout_log.html",form=form)
the first part doesn't seem to work
if current_user.is_authenticated:
if Admin:
return redirect(url_for('admin'))
elif Students:
return redirect(url_for('user'))
that's what they did in our school and guess what they fucked us up fr
whats the code
wait, i used quotes
yeah you dont need those lol
Hello! Im kinda new to python and i would like to ask how to make a chrome extension with python?
still getting the same thing without
Like a machine learned model to be integrated in a chrome plugin/extension
i think it works cause your route has the same name path
it's not necessarily referring to the python function under the route like url_for does
@login_required(redirect_field_name='login')
def view():
pass``` if am using something like this,how to customise context variable into "redirect_field_name" rather than 'next'
def get_data():
formi=Userform()
if formi.is_submitted():
student=Students(fullname=formi.fullname,personal_email=formi.personal_email,dialling_num=formi.dialling_num,branch=formi.branch,occupation=formi.occupation)
db.session.add(student)
db.session.commit()
return render_template("User/edit_page.html",form=formi)
```this block doesn't work
maybe try ```py`
return render_template("User/edit_page.html",{"form":formi})``
is this django?
flask
sorry
nah nah it's fine
def login():
if current_user.is_authenticated:
if Admin:
return redirect(url_for('admin'))
elif Students:
return redirect(url_for('user'))
form=Login_formcall()
if form.is_submitted():
if form.email_user.data.split('@')[1]=="direwa.com":
if Admin.query.filter_by(email=form.email_user.data,password=form.password.data).first():
login_user(Admin())
return redirect(url_for('admin'))
else:
flash("you don't exist")
elif form.email_user.data.split('@')[1]=="ecolewa.com":
if Students.query.filter_by(email=form.email_user.data,password=form.password.data).first():
login_user(Students())
return redirect(url_for('user'))
else:
flash("the User doesn't exist")
return render_template("Layout_log.html",form=form)
``` i also have a prob here
if current_user.is_authenticated:
if Admin:
return redirect(url_for('admin'))
elif Students:
return redirect(url_for('user'))
hi, i refactored my structure, and changed main.py to init.py . confirms it works locally but still getting this error on linode: https://paste.pythondiscord.com/ohedabejir.yaml
it's still unable to find autotrader module for some reason. here is my folder structure:
you installed autotrader
autotrader is actually a folder in my project
in my init, i need to import some stuff from it. it's failing on this import statement:
from autotrader.main import create_app
mm idk dude
it works locally, but it doesn't work when i push to linode
It becomes a public API
is there a reason to why sphinx randomly exits after 2%?
it occurs when i use an addtional html file
{% extends "!layout.html" %}
{% block extrahead %}
<script async src="arc-url"></script>
{% endblock %}
ah nvm i fixed it
just needed to remove extends
I'm confused about the value of color in the DOM. I created a button element and assigned it a hexidecimal color; however, when I console.log what the element.sytle.backgroundColor is, i get a rgb() value?? This is significant to me because i was putting in a conditional later on that would see if (e.style.backgroundColor === "#00000"), then do this, but I think that conditional isnt workign because of how its changing from hex to rgb in the DOM.
you would need to host it then
I know that
I need to do it from the RDP
suppose you developed an api on your local machine
and you want your local machine to be the host
how do you do it ? @gritty cloud
well first
get an external ip
buy a domain from someone
make sure ur computer will be running 24/7
ensure that you configure your dynamic, external ip (it will probably be dynamic) to act like a static one so that you don't have to type a different url the next day
and link it with your bought domain
a lot of pointless work imo
its like if you want electricity, you will go and build a power plant, configure wirings, and then deliver it to your house
@native tide
I have a bought a remote desktop from obh, so it has a domain and an ip obviously
And the ip is static
i want to start learning web development. should i learn javascript first, then html and css?
it never changes
Let me ask you this
I have the domain
and the Remote Desktop has an IP obviously
Are you saying that the only thing left ( after running the API on localhost ) is to route the requests to that domain to localhost ?
im not entirely sure :/
typically i just deploy on cloud
i feel that it is too much for too little to deploy on your local machine
The issue is my database 😦
Because I have a discord bot
And it's running on a remote desktop
and the bot's db is file based
Which is a problem
so I need an api to fetch data from that database
Unless you have another option
I want to keep eveything in one place
And if I move to a server based db
It's going to be a major refactoring 😒
So if you have an idea
please let me know
why not host your database somewhere else?
if you used a db which is apart of the Sqlalchemy ORM the rewrite shouldnt be to bad
I can't use an ORM because it's blocking
the bot is async
I haven't found an async ORM the last time I checked
I saw SQLAlchemy had something in beta
Idk if they released it
but where will I host the db ?
I don't see how Sqlalchemy ORM will solve my issue
Hi all, I am working on a project in Django and I have a slightly different structure than what I saw in all the tutorials I applied. It's all about "django admin".
Please all, If there is someone can helps me and has the time to do so, please send me a private message. Or at least mention me here.
Thanks in advance.
use an async version then?
like aiosqlite
asyncpg
So you're suggesting, refactor everything I have to use asyncpg, host the database on a server, then make an api and host it ( on digital ocean for example, and make that api query the db ? )
what's up channel
So it got released finally
Anyway that's not the problem
I'm just trying to find the best solution here
If you want, I can tell you what the problem is again
And you tell me what you think
well reading up on your previous message You should switch to a proper db rather than files (if im reading that correctly)
doesnt have to be a server setup
Sqlite would be enough
Basically if you want to keep the sqlite setup
I would advise writing a single controller that both things interact with
otherwise
use a server based DB
e.g. Postgres, MySQL, etc...
thats about your only reasonable way
Because opening up an IP is not advised ?
And making it public is just a pain in the neck
?
well not really, but the fact that SQLite is only really designed to be used by a single process at once on disk
At least, the way I'm thinking of
so if you have multiple things open the db you run into all sorts of issues with locks and performance etc...
personally i'd just bite the bullet refactor it to be an ORM maybe and then you can switch to what ever backend you like really without having to rewrite everything again in future
but You will likely have to refactor the code at one point or another, so might be better to just get it over and done with
And then once the refactoring is done and host the database on a server, I can just then use any service to deploy apis (like AWS' chalice or DigitalOcean's App platform) and link that API to the hosted server ?
pretty much
I don't know what's wrong.. can someone help me?
what's wrong in this please? 0.0
Hey guys, is there any worthy alternative for django-allauth? Or maybe allauth is still viable solution for user authentication?
@nimble loom firstly, exactly as your error states, you need to set the queryset class variable of your view.
Secondly,
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
if you're fetching data from some model, you need a QUERYSET
in your (I'm guessing class-based-view), write queryset = Model.objects.all()
where model is the name of your db model
FYI - finally figured it out. i needed to import package.file rather than just import file...😮💨
the serotonin rush after finally figuring out a bug after 3 days 🤤
for anyone else trying to get their flask app onto linode, use their tutorial: https://www.linode.com/docs/guides/flask-and-gunicorn-on-ubuntu/ , and be sure to import package.file rather than import file within your scripts lol
django is fun
any experienced django dev here i want some strong suggestion's
i have completed corey schafer's playlist , django begginer those 10 docs and have learned many topic's i have made a todo app , user sign up sign in forgot password change password reset and with profile part and stuff a blog app , now i wanted to learn advanced topics like cookies cart and payment management big projects advanced things , what should i do from where should i learn
Look into stripe for payment things and I'd suggest getting to know djangorestframework, token authentication and websockets
from where any yt tutorial
or only docs
idk react and i have 0 knowledge of js
how can i learn rest framework then for applying react vue and angular
if idk js
Djangorestframework has awesome documentation, so I'd suggest to learn from there. Once you know how to work the backend it's time to learn front-end, at least the basics of js
ohh bro and how can i learn stuff of cookies
I'm a vuejs guy but you gotta have experience with js/ts before learning a ui framework
bro but question is how will i do
rest framework
cez in that
we use 1 page technology
idk that so how can i learn
rest framework
if i recall correctly there is a udemy course regarding djangorestframework
if you want to learn drf or channels CodingEntrepeneurs on youtube has some nice yt videos
whats advantage of learning rest framework @wooden ruin in there we can use payment gateway
what is drf
drf = django rest framework
ohh
drf makes it easy to build an api
ohh got it
1 suggestion last pls @wooden ruin
ok
so i have covered many things now so i have 2 option now i should continue learning django or go to drf , what should i do i have now a good exp of django framework should i go to learn drf now or make e-commerce site in this simple django only
how to mandle cookies
what is asgipy wsgipy
i dont saw any use of them
i suggest learning djangorestframework because it's widely used among backend developers
asgi stands for asynchronous server gateway interface
10 to 12 hrs a day
i never used it
django uses wsgi by default when u deploy (i.e. using gunicorn when setting up for production). when you use websockets for django channels it requires asgi which provides support for asynchrous stuff (the counterpart for this is daphne as opposed to gunicorn)
cookies part is also ez in rest framework
oh
it means im going right rn
i didnt missed anything
sounds good
cez i have not learned deployment so ohkk
yes devops is important to learn, at least the basics i'd say
i mostly play with my code
i learned to delete object in model
so for fun i added delete user option
and deleted the main admin (owner )

yea its really nice getting to know all those cool features
hey
hello how can we help u
hey
btw look into using disabled in the default django user model instead of delete, the docs say that deleting users can tend to break relationships

Can anyone help me with django?
I just started learning
Best to put your question in the chat. Better if you put a formatted code sample.
Ok sure
So basically i just started
And i was having trouble printing the data from my db on the webpage
I've almost tried everything but it just wouldn't print whts inside the django template for loop
this is views.py
from django.shortcuts import render
from .models import Post
# Create your views here.
def home(request):
data = Post.objects.all()
print(data)
return render(request,'index.html',{"posts": data})
# return render(request,'index.html',{})
index
{% for post in posts %}
here
{{ post.title }}
{{ post.content
}}
{% endfor %}
here i've tried using <p> <li> and even tried creating a table
but the output is not visible
Ping me if u want anyother file
I'm a little rusty with django.
I was finding an example to compare though I found one with class based views https://docs.djangoproject.com/en/3.2/ref/class-based-views/generic-display/
Ya its seem similar
Hey wait
It worked😶
Automatically
But it was not woeking yesterday
I wasted 2-3hrs on this stupid thing
@clever bronze how can i help
@dusk portal its solved
thanks btw
it doesn't submit in the database
@app.route('/',methods=["GET","POST"])
def login():
form=Login_formcall()
if form.is_submitted():
if form.email_user.data.split('@')[1]=="direwa.com":
if Admin.query.filter_by(email=form.email_user.data,password=form.password.data).first():
ADmin=request.form["email_user"]
session["Admin"]=ADmin
return redirect(url_for('admin'))
else:
flash("you don't exist")
elif form.email_user.data.split('@')[1]=="ecolewa.com":
if Students.query.filter_by(email=form.email_user.data,password=form.password.data).first():
current_student=Students.query.filter_by(form.email_user.data)
session["student"]=current_student
return redirect(url_for('user'))
else:
flash("the User doesn't exist")
return render_template("Layout_log.html",form=form)
i tweaked the code a little bit
def get_data():
formi=Userform()
if "student" in session:
current_student=session["student"]
if formi.validate_on_submit:
new_change=Students.query.filter_by(email=current_student)
new_change.fullname=formi.fullname
new_change.personal_email=formi.personal_email
new_change.dialling_num=formi.dialling_num
new_change.branch=formi.branch
new_change.occupation=formi.occupation
db.session.commit(new_change)
return render_template("User/edit_page.html",form=formi)
so the thing is the submitfield didn't work
def get_data():
formi=Userform()
if "student" in session:
current_student=session["student"]
if formi.is_submitted and request.method=="POST":
# current_student.fullname=formi.fullname
# current_student.personal_email=formi.personal_email
# current_student.dialling_num=formi.dialling_num
# current_student.branch=formi.branch
# current_student.occupation=formi.occupation
# db.session.commit()
print(current_student)
return redirect(url_for('user'))
return render_template("User/edit_page.html",form=formi)
C:\Users\Hamza\Desktop\PFA\FLASKPROJ\lib\site-packages\flask_sqlalchemy_init_.py:872: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning.
warnings.warn(FSADeprecationWarning(
- Debugger is active!
- Debugger PIN: 142-229-564
- Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [11/Jul/2021 12:01:03] "GET /user/edit_profile HTTP/1.1" 200 -
127.0.0.1 - - [11/Jul/2021 12:01:03] "GET /static/css/style_user.css HTTP/1.1" 304 -
127.0.0.1 - - [11/Jul/2021 12:01:03] "GET /static/img/eWA_Logo.png HTTP/1.1" 304 -
didnt print the current_student
is student in the session? the print only execute if it is, else it doesnt
just make an else statement to check
i made an else statement and i loged in when i click on the edit profile i stay in the same page
isn't the student in the session even tho i added him in the login
i click on it but nothing happens
what are you saying here? that the get_data() function is never reached?
exactly
so the problem is not here then
should i pass the whole code
no, just the one that's linked to the button
the code that's linked with the link is the one i showed now
this is the view function that's linked with the button
{% extends "Layout_user.html" %}
{% block content %}
<section class="content">
<h2 id="welcome">Welcome to your Dashboard</h2>
<div class="info">
<div class="userinfo">
<img src="{{ url_for('static',filename='img/imageblank.png') }}" alt="profilepic">
<a href="{{ url_for('get_data')}}">edit profile</a>
</div>
</div>
</section>
{% endblock %}
what's the route for it?
what happens when you visit it manually?
@app.route('/user',methods=["GET","POST"])
this is the route for the user or the student
@app.route('/user/edit_profile',methods=["GET","POST"])
this is the route for the edit page to edit the info
what happens when you visit here /user/edit_profile'
i get back to user/ i can't acces the page
it instantly redirects?
yeah
return redirect(url_for('user'))
comment out this line and try again, tell me what happens
it went to the edit page
are you using flask_wtf?
yeah
wtforms
from flask_wtf import FlaskForm
from wtforms import BooleanField,PasswordField,StringField,RadioField,SubmitField,SelectField
from wtforms.fields.html5 import TelField
from wtforms.validators import DataRequired, Email
class Login_formcall(FlaskForm):
email_user=StringField('Username',validators=[DataRequired(),Email()])
password=PasswordField('Password',validators=[DataRequired()])
remember=BooleanField('Remember me')
submit=SubmitField('Login')
class Userform(FlaskForm):
fullname=StringField("Fullname",validators=[DataRequired()])
personal_email=StringField("Email",validators=[DataRequired()])
dialling_num=TelField("Tel/num",validators=[DataRequired()])
branch=RadioField("Branch",choices=[("Dev","Dev"),("Des","Des")],validators=[DataRequired()])
occupation=SelectField("Occupations",choices=[("Work","at work"),("Freelance","freelance"),("Unemployed","no job"),("Studying","Still studying")],validators=[DataRequired()])
SUB=SubmitField("Submit")
also the submit in the userform doesnt work
cuz when i enter data and submit it it doesn't push to the database
change this if formi.is_submitted and request.method=="POST":
to
if formi.validate_on_submit():
tried it but not nothing i've been stuck in this prob for 3 days now
what do you mean?
i'm asking you to try it now
i just did again and nothign
hop in voice and show me what's happening
where can i get django related help?
i'm in voice help 0
@sick glacier here
@opaque rivet : thanks
uh hey ```File "C:\Users\Hamza\Desktop\PFA\Flaskiproject\routes.py", line 39, in user
return render_template("User/Homepage.html",student=current_student)
UnboundLocalError: local variable 'current_student' referenced before assignment
```py
@app.route('/user',methods=["GET","POST"])
def user():
if "student" in session:
current_student=Students.query.get(session["student"])
return render_template("User/Homepage.html",student=current_student)
```how can i correct this
that's happening because if that if statement is false, the function would not be able to return current_student since it wouldn't be defined. you can either:
- assign it a dummy value above the if statement, or
- tab over the return statement so that it's within the if
I have made a location tracker but I am getting this error
I am getting those yellow lines
and what does your editor say those yellow lines mean?
when you put your cursor on them, or in your Problems tab (if this is vscode)
_name_ should be __name__ btw
and services_operator is typoed in the one highlighted
and your import can't be resolved, so look at how to do imports and check to make sure you've set up phonenumbers correctly to be imported
So you have 2 typos and phonenumbers isn't imported because you've not created it, installed it, or something.
_main_ should also be __main__
I had done pip install phonenumbers
Yes I did it
so is the only error you have now about phonenumbers?
yes
still fix _main_ to __main__ (no error showing cause its a string being checked but check out https://www.freecodecamp.org/news/if-name-main-python-example/ )
From where you think you installed phonenumbers module, run pip list
You should really be doing all of this in a venv btw because otherwise you're installing modules at the global level.
can you use f'string' in jinja
<h1>{{ print(f"fullname:"{student.fullname}) }}</h1>
<h1>{{ print(f"personal-email:"{student.personal_email}) }}</h1>
<h1>{{ print(f"dialling-number:"{student.dialling_num}) }}</h1>
<h1>{{ print(f"branch:"{student.branch}) }}</h1>
<h1>{{ print(f"occupation:"{student.occupation}) }}</h1>
then write it plaintext
Do I need double underscore in
if __name__=="__main__":
<h1>fullname: {{student.fullname}}
@warm igloo
??
this might be a better place than general to ask for flask/celery help haha. please let me know if not
trying to set up some way to see print statements.
I have a logger set up for the tasks, where it's just a matter of get_task_logger, but I'm not sure what I need to do to see print statements in Flask routes
actually...may have found the answer already
I think it lies in Flaskland somewhere as opposed to celery
what does it say when you hover over it?
lol what yellow lines
@thorn igloo
ok, what happens when you run your program? does it run or not?
ok wait I will send you
ohh its working now
srry
But the yellow lines are still there
It's probably the linter doing a bad job
Needed some beginner help with Python / Django:
Is it possible for user to create two objects from the same form? For example, am trying to create a to-do list webapp. When a user creates a task, they should have the option to:
-
Choose from existing tags (another object that has many:many relationship with 'task', or
-
Create a new 'tag' if the existing ones don't suffice.
Is it possible to do this from single form? Currently, when I create the form for 'task' using Model form, all it allows the user to do is (1).
how can i eliminate this and make instead of choose file make it like a field to drop items in
Hello so, idk whats the problem here
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid:
username = form.cleaned_data.get('username')
messages.success(request,f'Account created for {username}!')
return redirect('blog-home')
else:
form = UserCreationForm()
return render(request,'users/register.html',{'form':form})
even tho I have used cleaned_data after is_valid, it still gives me this error
I hate programming, I found it, its the "()" on is_valid
Does Django have support for mongodb?
form.is_valid()
I think there is a external library you need to use if you want to use Django with mongodb
yes
btw
db.add_column(upload)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'SQLAlchemy' object has no attribute 'add_column'
I've not tried mongo as the backend for Django, but I did investigate for a project: Djongo https://pypi.org/project/djongo/
what is the standard way for terminating a task using celery?
is it really revoke(task_id, terminate=True, signal='SIGUSR1')? that seems really obtuse
like, I'm looking for something which doesn't abuse signals, like how they expect people to be able to end a running task
this didn't seem to give me anything definitive:
https://docs.celeryproject.org/en/latest/userguide/workers.html#revoke-revoking-tasks
what do you mean doesn't abuse signals?
The default is sigterm and sigterm can be handled or ignored. The TERM goes to your task, and it is up to your task to handle it gracefully (or not-gracefully depending on what you want to do)./
Django?/
hey i got a small prob here
@app.route('/user',methods=["GET","POST"])
def user():
if "student" in session:
x=Students.query.get(session["student"])
form=Userform()
if form.validate_on_submit():
x.upload=form.uploadwork.data
db.session.commit()
return redirect(url_for('user'))
else:
return redirect(url_for("login"))
return render_template("User/Homepage.html",student=x,form=form)
it doesn't upload in the database
hi guys, i have a problem in django: TemplateDoesNotExist at /
homepage.html ,, when i try to runserver command
i tried the common solvings but they are not working
can anyone help this
it means there’s an error with your code
i kinda get it but the student model have upload
class Students(db.Model,UserMixin):
id=db.Column(db.Integer(),primary_key=True)
fullname=db.Column(db.String(50),unique=True,nullable=False)
email=db.Column(db.String,unique=True,nullable=False)
personal_email=db.Column(db.String,unique=True,nullable=False)
password=db.Column(db.String(),unique=True,nullable=False)
dialling_num=db.Column(db.String(),unique=True)
branch=db.Column(db.String())
occupation=db.Column(db.String())
upload=db.Column(db.String())
127.0.0.1 - - [11/Jul/2021 22:42:16] "POST / HTTP/1.1" 302 -
Student:Students.id Students.fullname Students.dialling_num Students.branch
when i use print idk why it's not displayed even tho i made it from the cli and got it in the db
where is homepage.html file located? is it at ../myapp/templates/myapp/homepage.html? try referencing it with myapp/homepage.html. "myapp" is a placeholder for your app name. In code templates path are relative to some directory defined in TEMPLATES setting, the default setting makes django search templates in ../myapp/templates directory for all installed apps, to avoid template name collision between different apps you create a subfolder with app name and put your templates there, so you reference it with appname/mytemplate.html.
from first_app import forms
from first_app.models import AccessRecord
# Create your views here.
def index(request):
webpages_list = AccessRecord.objects.order_by('date')
date_dict = {'access_records': webpages_list}
return render(request, 'index.html', context=date_dict)
def help(request):
my_help = {'insert_help': "hey, i need help!"}
return render(request, 'help.html', context=my_help)
def form_name_view(request):
form = forms.FormName()
if request.method == 'POST':
form = forms.FormName(request.POST)
if form.is_valid():
print("Verification Done")
print("Name:" + form.cleaned_data['name'])
print("Email:" + form.cleaned_data['Email'])
print("Comment:" + form.cleaned_data['comment'])
return render(request, 'forms.html', {'form': form}) ```
from django.forms import Textarea
class FormName(forms.Form):
name = forms.CharField()
Email = forms.EmailField()
comment = forms.CharField(widget=forms.Textarea) ```
i am not getting any error but the form_name_view method doesn't seem to work
sorry for the mess!
what does not works? you can access it from browser?
yeah the web page opens but when i submit it doesn't print out ("verification done')
i am just trying to check if the "POST" method works
and the form does not displays any error?
how is your form template? you followed django's tutorial?
i am learning from a course on udemy.
form template is working fine
btw the latter is the forms.py file
and above it is views.py
class Uploading(FlaskForm):
uploadfile=FileField("upload",validators=[FileRequired(),FileAllowed(["jpg","png","pdf","txt"])])
Submitting=SubmitField("Submit")
@app.route('/user',methods=["GET","POST"])
def user():
if "student" in session:
current_student=Students.query.get(session['student'])
print(current_student)
form=Uploading()
if form.validate_on_submit():
current_student.upload=form.uploadfile.raw_data
db.session.commit()
return redirect(url_for('user'))
else:
return redirect(url_for("login"))
return render_template("User/Homepage.html",student=current_student,form=form)
class Students(db.Model,UserMixin):
id=db.Column(db.Integer(),primary_key=True)
fullname=db.Column(db.String(50),unique=True,nullable=False)
email=db.Column(db.String,unique=True,nullable=False)
personal_email=db.Column(db.String,unique=True,nullable=False)
password=db.Column(db.String(),unique=True,nullable=False)
dialling_num=db.Column(db.String(),unique=True)
branch=db.Column(db.String())
occupation=db.Column(db.String())
upload=db.Column(db.String())
def __init__(self,fullname,email,personal_email,password,dialling_num,branch,occupation,upload):
self.fullname=fullname
self.email=email
self.personal_email=personal_email
self.password=password
self.dialling_num=dialling_num
self.branch=branch
self.occupation=occupation
self.upload=upload
def __repr__(self):
return f'Student:{Students.id} {Students.fullname} {Students.dialling_num} {Students.branch} {Students.upload}'
so this is my code and when i try to submit some file to the database it doesn't wanna be pushed to the data base
what do you mean by read
you wanna present the data right
i guess you should do this
fileread = filesubmit.file.data()
```since it doesn't have such thing as read and you want to display the data that you got from the field right
if not and you want to get it from the database i guess you should do something like this
x= Filesubmitproject.query.filter_by(file=fileread)
at least from what i understood
what is your .read() line I didn't see it in the code above
Not sure if this is the place to post this, but any thoughts?
Looks like your xpath is wrong and that element doesn't exist?
Wait what exactly do those words mean haha?
Off top of head I think you need filesubmit.file.data.read()
let me go look at a flask app I have with a file upload, see how I did it cause I can't remember atm
dude, I'm an "architect" and I've spent hours recently looking for a single ' that was effing up my world. It happens to all of us. 😄
I'll go find my code too just to be sure
wait did it work?
lmfao
welcome
pulled that shit out of the air
haha been there
uhoh
well, they're bytes yes
you gonna store them as a blob in the db?
make sure you save a filename or at least mimetype with them too
cause that will matter
I have in the past as another column. Main thing when you want to print out the blog back to an image, you'll need to say "oh save this to disk as a .jpg" or "stream this to the client as a .jpg". But if your clients can upload all those different file types, how will you know what to send them back?
For instance, you could store the original filename or extension and just use that when you spit it back out. And if you're streaming it back to them, you may need to set the Content-type to image/jpg so the browser knows what to do.
But before you even go there, give it a try and see what the hell happens
🙂
yayyyy!!!
@mossy osprey Did you figure out your xpath syntax?
Lmaooo all good @fair shale
Nope. However I apparently don't have an xpath issue anymore. My issue now is: ```selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[4]/div/div/div[2]"}
same issue
So just a bit of a context. I'm trying to write a simple script that returns a list of followers from one of my Instagram accounts. So I don't think there's an Instagram Python API that I can use, I'm just using selenium.
Bruh I'm blind.
I saw the xpath after you just pointed it out @warm igloo. Anyway what exactly is an xpath?
so, you're trying to select some element on the page and it is saying "sorry, that isn't there"
you need to catch that exception and do something accordingly
Oh so the element "/html/body/div[4]/div/div..." doesn't exist for some reason right?
xpath is just a syntax for selecting elements from a tree of nodes like in html or xml
right, I'm guessing you're using selenium commands and trying to find some div/button/element/whatever and this is saying "you're wrong, that's not there"
Hey, I'm working on one thing regarding Ubisoft and I need to connect into account using email and password and get authorization, but unfortunately I'm struggling with it. I found the same thing that I need in C# but unfortunately I dunno it and I can't really make it in python for some reason, any ideas?
var basicCredentials = Convert.ToBase64String(
Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["mail"] + ":" + ConfigurationManager.AppSettings["password"]));
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
Headers = {Authorization = new AuthenticationHeaderValue("Basic", basicCredentials)},
RequestUri = new Uri("https://public-ubiservices.ubi.com/v3/profiles/sessions"),
Content = new StringContent("{\"Content-Type\": \"application/json\"}", Encoding.UTF8,
"application/json")
};
keep in mind for instagram their HTML might not be rendered and may all be client side generated with JS so you'll need to make sure whatever you're using as your selenium browser engine is rendering the JS of the page too (I think by default it should be doing that but I can't recall atm)
I see. So how do I know what specific button /html/body/div[4]/div... corresponds to? I will admit I didn't write this script originally. Someone else did, and I'm just using it mostly as a learning experience lol.
@mossy osprey do you have some code you can share?
sure
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
just in case
Do you want me to send the entire thing or just a fraction? (the entire thing is 73 lines)
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Put the 73 lines there
or repl.it or something like that
I write a lot of spiders using selenium, beautifulsoup, etc so hoping I can help you
I'm working on script that will login into account and scrapes stats of it
Actually something I need to remind both of you: make sure you are not violating the TOS of the site you are trying to scrape.
And I need to get auth of that account as well
https://paste.pythondiscord.com/ijuvenozuy.py @warm igloo Lemme know if that shows up
If I may ask, what kind of account? Cuz i'm doing like almost the same thing lmao (mine is instagram)
Ubisoft
There's explained everything
What's ur problem?
just trying to return a list of users from one of my accounts. It's more of a learning experience/really simple project. Nothing deeper than that right now.
@native tide You can make those same calls with python. Take note of the steps and the headers and make the same request to the same url. Try to write the code and I'll try to help you, but I can't do a direct translation for you.
I have tried it using many ways but I have no clue tbh
email = ""
password = ""
r = requests.post("https://public-ubiservices.ubi.com/v3/profiles/sessions", auth=(email, password))
rData = r.json()
print(rData)
And other ways that are described in docs (https://docs.python-requests.org/en/master/user/authentication/)
@mossy osprey Since you borrowed this code and its not yours, what could be happening is that particular layout has changed and the xpath is now incorrect cause the elements on the page you're looking at are different now.
So for instance the page could have been "<div>Hello Swift!</div>" last week but this week is "<div><span>H</span>ello, <em>Swift!</em></div>" this week so the code says "gimme the div at this xpath" and of course .. the path is now different.
Ahhhh that makes sense. So how would I be able to retrieve the correct "layout" and translate that into workable code?
Usually how I do it is 'Inspect Element' in my browser. Depending on which browser you can see the xpath at the bottom of the console (though not in xpath syntax necessarily).
Ooh, in Firefox I can right click on an element in the inspector and then copy the xpath from there: /html/body/header/div/div[1]/a[2]/span for instance that came from an element on a page I was just on
So I went to instagram and popped open the followers modal and selected the xpath of the div containing my list of followers: /html/body/div[5]/div/div/div[2]
Or rather this: /html/body/div[5]/div/div/div[2]/ul/div is "further down" and closer to the data
Reminder: make sure the script you're making is opening the modal window too or the element you're searching for won't exist
tricky stuff scraping from javascript heavy front ends
@warm igloo Did you do this in firefox or chrome? rn, i'm doing this in chrome
I could try in firefox
I'm in FF right now. Don't have Chrome on this box as its just my gaming box. 🙂
I'm sure Chrome is similar though
Any ideas on this? I dunno how to make these same requests since I barely understand csharp
private static async Task<UbisoftToken> GetToken()
{
_httpClient.DefaultRequestHeaders.Add("Ubi-AppId", "2c2d31af-4ee4-4049-85dc-00dc74aef88f");
_httpClient.DefaultRequestHeaders.Add("Ubi-RequestedPlatformType", "uplay");
_httpClient.DefaultRequestHeaders.Add("user-agent",
"Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3");
Console.WriteLine("Connecting to the Ubisoft Servers.");
var basicCredentials = Convert.ToBase64String(
Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["mail"] + ":" + ConfigurationManager.AppSettings["password"]));
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
Headers = {Authorization = new AuthenticationHeaderValue("Basic", basicCredentials)},
RequestUri = new Uri("https://public-ubiservices.ubi.com/v3/profiles/sessions"),
Content = new StringContent("{\"Content-Type\": \"application/json\"}", Encoding.UTF8,
"application/json")
};
var response = await _httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
throw new UnauthorizedAccessException("Unable to retrieve authentication ticket. Thanks ubisoft mf!");
return JsonConvert.DeserializeObject<UbisoftToken>(await response.Content.ReadAsStringAsync())!;
}
This is whole function
oh yeah you'll need to add all those other headers to your python too, not just the auth
the appid, uplay one, etc
I'm looking for a learning partner who would like to contribute to my Django web app project by creating a modern design for a simple dashboard.
I'm a back-end developer and not experienced with JS nor have the design skills for sexy CSS.
If you would like to help please send a DM with your portfolio (if you have one, if not that's fine too)!
How should I do it?
@warm igloo so I did what you said: right-click, inspect element. But this doesn't like an xpath to me?
I took your advice and logged into Instagram on Firefox ^^
Or u can use some addon such as ChroPath
headers = {
'Ubi-AppId':'880650b9-35a5-4480-8f32-6a328eaa3aad',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36',
'Ubi-RequestedPlatformType':'uplay'
}
r = requests.post("https://public-ubiservices.ubi.com/v3/profiles/sessions", auth=(email, password), headers=headers)
rData = r.json()
print(rData)
I tried this but it still doesn't work
Normally there's Authorization in headers too and there's the auth token but I need to login using email and password in this case
And I'm getting The Authorization header is missing error since I don't have any there
Can anyone help me?
I am unable to install any python module thru pip from Anaconda prompt
I remember that conda has different ways to install the same.
pip is replaced to conda in conda
something like that perhaps
Command for mysql connector:
pip install mysql-connector
according to this guide, you still need to use pip though
just in different console
Check your connection
can we make websites for discord bots in python?
can anybody recommend me some resources to learn CSS
You need a templates folder
ohh new folder?
yah...
um alright but where
oh
It will make sense later. And it makes it easier to organize files as the project grows.
Hello guy, is there any module for bypass cloudflare? I tried this module https://github.com/VeNoMouS/cloudscraper but it doesn't work.
nvm fixed
how do i make a button in html when clicked does something using python code
in pure html, you make submit form https://www.w3schools.com/html/html_forms.asp
which will make POST request to the same page you are in. it will allow you to execute python code
in flask where you are, you should use flask forms
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iii-web-forms
im not making a submit form
then you attach javascript to button
that makes fetch request to your python api
as far as I know there are only two ways. I can't offer you third one.
why
he just explained that there are two ways??
it's either you submit a form or you make ajax calls from JavaScript
anyone know about this?
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
!rule 6
I will ask other channel about bypass cloundflare
@tawny gazelle better read #rules
!rules
The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.
any way without js
wdym by form
Hello guys, Which module I should use for connecting database(i.e MySql)?
which one is the best python module for connecting database?
what is your framework
anyway, SQLAlchemy is a nice average choice
Pure python script
Thanks for your advice 🙂
have any one tried getting previous day data from openweather API
Hi,
I'm trying to populate the admin field directly from the created_by field on save of a group instance though I'm getting error "direct assignment to the forward side of a many-to-many set is prohibited" How can I work around this ?
Here's my code
class Group(models.Model):
group_name = models.CharField(max_length=200, blank=True)
description = models.TextField(
help_text='Describe this group...', max_length=350, blank=True)
admin = models.ManyToManyField(
"profiles.Profile", blank=True, related_name='group_admin')
members = models.ManyToManyField(
"profiles.Profile", blank=True, related_name='members')
posts = models.ForeignKey(
"posts.Post", blank=True, on_delete=models.SET_NULL, null=True, related_name='group_posts')
created_by = models.ForeignKey(
"profiles.Profile", on_delete=models.SET_NULL, null=True, related_name='group_creator')
created = models.DateTimeField(auto_now=True)
Hello,
I just have a simple question regarding Django administration. I know how it functions and have explored it a bit. Django Admin offered all sort of CRUD features directly into my database. Now I am supposed to build a simple web API for my client where I am supposed to do simple CRUD tasks. If Django Admin directly offers it, should I use the libraries that the django admin uses or do i need to write codes for the client myself? Also, for whom is Django admin targeted for? Is it for server people or developers only? Or can it be passed to the client? I have done alot of API's in NOdejs but I have recently started Django so I am a bit confused on the Django Administration. Any help would be appreciated.
simple recommendation. don't use django admin as main thing for CRUD
django admin is targeting being used only by devs or moderators
Hello everyone, I have simple, maybe not, question for Django CMS. I have a major error and don't know where to look. So the issue is following:
- I am using Django CMS show_menu, using my own template etc.
- I have a specific menu tree that I have on Django Admin panel with all pages and menu items, half of which are marked as they should not be visible in menu
- When I open webpage that I am working on, it shows me menu and all items that are in that menu tree, like all of them, including the items, that have been switched off.
The tag i am using to show menu is following: {% show_menu 0 100 100 100 "*link to template*"%}
Could you please assist and tell me where could possibly error be? Thank you!
Hi ,
I am struggling with django errors, i tried many things to solve, but every time, i got a new one. Although i am doing same things in the video , i got an error message, i don't know why it is like that:
Bump
Um, what?
I'm trying to login into account lol
Using email and password instead of auth token
thats malicious pretty sure
assets = db.execute("SELECT symbol, action FROM account, SUM(shares) WHERE action = buy - SUM(shares) WHERE action = sell AS shares WHERE userid = ? GROUP BY symbol", session["user_id"])
i think it's not allowed to have multiple WHERE in SQL? there's a syntax error, how do i achieve this effect
i want to select the data from account table to get data for bottom
Most SQL languages will allow a case statement that would do a if statement that will be more suitable.
For example in PostgreSQL
with processing (
SELECT
symbol,
CASE action
WHEN 'buy' THEN shares
WHEN 'sell' THEN shares * -1
ELSE null
END as shares
FROM account WHERE userid = ?
)
Select symbol, SUM(shares) from processing group by 1;
This is a combination of a CTE so I could logically seperate the query and do the group by afterwards as you can't always do it at once...
Hey, so I'm basically making script that logins into Ubisoft account using email and password, but I don't know how to do it.
headers = {
'Ubi-AppId':'880650b9-35a5-4480-8f32-6a328eaa3aad',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36',
'Ubi-RequestedPlatformType':'uplay'
}
r = requests.post("https://public-ubiservices.ubi.com/v3/profiles/sessions", auth=(email, password), headers=headers)
rData = r.json()
print(rData)
Normally there's Authorization: 'token' in headers and there's the auth token but I need to login using email and password in this case and I dunno how to write the syntax in that case. (I'm building a stat checker, not anything malicious or whatever)
hm
You would first have to make a post to the login / signup url
this is an interesting channel
so what can i use to tell what should happen when someone clicks on a button with Python
Then reuse the auth token they give you
considering the button was written in HTML and styled with CSS
Assuming they use tokens amd not sessions
is Flask the way to go?
This is the "thing" that I need but in csharp, and I barely understand it so I'm really not able to convert it into python
private static async Task<UbisoftToken> GetToken()
{
_httpClient.DefaultRequestHeaders.Add("Ubi-AppId", "2c2d31af-4ee4-4049-85dc-00dc74aef88f");
_httpClient.DefaultRequestHeaders.Add("Ubi-RequestedPlatformType", "uplay");
_httpClient.DefaultRequestHeaders.Add("user-agent",
"Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3");
Console.WriteLine("Connecting to the Ubisoft Servers.");
var basicCredentials = Convert.ToBase64String(
Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["mail"] + ":" + ConfigurationManager.AppSettings["password"]));
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
Headers = {Authorization = new AuthenticationHeaderValue("Basic", basicCredentials)},
RequestUri = new Uri("https://public-ubiservices.ubi.com/v3/profiles/sessions"),
Content = new StringContent("{\"Content-Type\": \"application/json\"}", Encoding.UTF8,
"application/json")
};
var response = await _httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
throw new UnauthorizedAccessException("Unable to retrieve authentication ticket. Thanks ubisoft mf!");
return JsonConvert.DeserializeObject<UbisoftToken>(await response.Content.ReadAsStringAsync())!;
}
bro
As far as I understand this script makes an htp client with the necessary credentials then sends the request
Then throws an error if the request fails
Would u be able to show me the syntax of how it should be in python? I was trying to do this yesterday for over 3 hours but I have no clue
That's what I tried
Many times using many ways
Unfortunately they do not
Hm
mate, you can google for that
if you can't find it what makes you think i will?
just look in the jinja2 documentation
ohk
oh thanks is there a way to do it with sqlite3
cuz my ide supports that
Thank you. Can I build admin portal out of it though? And make Api for client only?
django admin to be used for admins? sure ;b that's why it is called django ADMIN 😉
second question is not providing enough information to answer
@inland oak I researched it a bit and your verification made everything clear. Thanks again.
bumpp
Anyone worked with Django channels? Does it generally require an ASGI server in production for the entire project?
I'm looking to create subscriptions with GrapQL to Django, but it looks like there's a lot of work on the backend to get that working.
5 seconds of googling say its built ont ASGI
even its depended libraries are mentioned
Yea I've read it, I'm more curious about people's experience with it. How difficult it was to setup and get running in production, et.
shrugs. The page mentions it uses Daphne ASGI
I heard Daphne is made specifically for Django
https://github.com/django/daphne
reading this description...
it was actually made specifically for Django Channels ;b
Hello people I am working on making a RPC like framework using Zeromq. Any suggestions are welcomed!
https://github.com/Ananto30/zero
how to debug django on visual studio code
i don't see any option to choose django 😦
can someone please help me out
django is a python framework bruh
i mean on visual studio code
what do you mean by debug is this context?
Django Tutorial for Beginners - Learn Django for a career in back-end development. This Django tutorial teaches you everything you need to get started.
- Get the complete Django course (zero to hero): https://bit.ly/3A7l7qj
- Subscribe for more Django tutorials like this: https://goo.gl/6PYaGF
Other resources:
Python Tutorial for Beginners: ht...
watching from 36:40
for him it is showing django
for me it is not
let me check
make sure your current active window is a python file
i tried it and the django option is there for me
you have the python extension installed?
i it's returning it because that's what you are telling it to return
there is actually an option to run django 😉
but it is not needed in my opinion
because there is option to run pytest ;b
debugging pytest is the only needed thing in my opinon
no point in debugging launched application
look here
see how x wasnt affected
but the function needs to be called first before the change can happen, keep that in mind
I have a question please
I have a list of dataframes
I want to render each one in one tab
of a html flask project template
The dataframe is very complex in syntax it is muti indexed
in the usual way to return only one dataframe not a list of dataframes in one template I used dataframe.to_html()
return render_template(
"table_tfidf_trame.html",
mot=word,
liens=nb_links,
tables=[
output_f.to_html(
classes="table table-striped table-hover table-sm",
header="true",
justify="center",
)
],
)
and in the html I used
{% for table in tables %}
{{ table|safe }}
{% endfor %}
good night, i wanted to create a plugin module in jpython for the autopsy tool. fetch data from SQLLITE databases.
hi, so i have multiple files that i want to return back to the web browser, except these files are open with BytesIO, is there a way to do this and for context i am using flask
found a way no need to help me anymore
I'm looking for some help creating a parent/child relationship with a single model. Essentially I have a model called Systems which can have children as subsystems (which can themselves have subsystems). I want to create a many-to-many relationship between them, but I'm getting errors when I try to use this
class System(models.Model):
system_name = models.CharField(max_length = 100)
description = models.CharField(max_length = 500)
pub_date = models.DateTimeField('date published')
stages = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(20)])
class Subsystem_relation(models.Model):
parent = models.ManyToManyField(System)
child = models.ManyToManyField(System)
Anyone with a helping hand?
Consider me a complete noob because I totally don't how to do what I am about to say or even if I'm in the right place for it, can we upload images to some sort of a temporary server or website atleast 1 image per second with enough speed that discord can render it like a really low fps game in an embed yes this is a discord bot project idea
This is completely indirect to the discord.py library
Mate, this has got nothing to do with the library, just that this is for a bot. What I want to do is to upload an image to a web of sorts and be able to render it from discord with an embed. So is it possible/is there a website or library Which can help me upload an image to a database and handle it fast enough?
Oh
Thanks .. I'll try to do something,
Thanks for ur effort
does anyone know how to get started with python web dev?
I am going through the official flash tutorial for the first time.
It seems that string interpolation doesn't work?
def show_user_profile(username):
# show the user profile for that user
return f'User {escape(username)}'```
I get invalid syntax
What is your version of Python?
Python 3.9.6
from markupsafe import escape
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Index Page</p>"
@app.route('/hello')
def hello():
return "<p>Hello World</p>"
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return f'User {escape(username)}'```
are you sure that's the version of Python that's executing this script?
ModuleNotFoundError: No module named 'flask'
yeah you didn't install flask on your python 3.9 version
do
pip3 install flask
or whatever you need to install it on linux
you're on linux, right?
no mac
can you please do
from sys import version
print(version)
in your code and tell me what it says when you do
python3 hello.py
like what version of Python does it say
3.9.6 (v3.9.6:db3ff76da1, Jun 28 2021, 11:49:53)
[Clang 6.0 (clang-600.0.57)]
Traceback (most recent call last):
and then there is this error of flask being unknown right
ModuleNotFoundError: No module named 'flask'
but flask works
I can do index and hello routes
but when is gets to the formating it says it can't do it
but I know it is available in this verison of python
yeah so, PyCharm starts python2 for some reason
and flask isn't installed for python3 for some reason for you
i don't know
are you in a virtual environment
yeah I am just bc I am following allow the tut
Javascript question
did it tell you to run these or something similar
How can I detect when an event has completed propagation
note python3
then that
all that before you pip3 installed flask
or just pip i guess
yeah I did all three steps and copied the lines
https://stackoverflow.com/questions/31252791/flask-importerror-no-module-named-flask @pallid spade maybe follow this thread
I'm following the Flask tutorial here:
http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
I get to the point where I try ./run.py and I get:
Traceback (most recent c...
Requirement already satisfied: flask in ./venv/lib/python3.9/site-packages (2.0.1)
Requirement already satisfied: click>=7.1.2 in ./venv/lib/python3.9/site-packages (from flask) (8.0.1)
Requirement already satisfied: Werkzeug>=2.0 in ./venv/lib/python3.9/site-packages (from flask) (2.0.1)
Requirement already satisfied: itsdangerous>=2.0 in ./venv/lib/python3.9/site-packages (from flask) (2.0.1)
Requirement already satisfied: Jinja2>=3.0 in ./venv/lib/python3.9/site-packages (from flask) (3.0.1)
Requirement already satisfied: MarkupSafe>=2.0 in ./venv/lib/python3.9/site-packages (from Jinja2>=3.0->flask) (2.0.1)
going to take a break
I have no idea
(venv) ~/PycharmProjects/flask-tut $ python3 hello.py
does it mean it worked?
there is no output
oh wait did you remove the line where it runs it like that
hold on I got a friend calling that is programmer
@pallid spade try just running flask run now
I uninstalled flask and reinstalled and it worked? I think
works now? but I don't know what excatly fixed it
How can I detect when a javascript event object has finished propagating?
I'm writing a program that creates a virtual/proxy DOM in python to represent a living webpage. Whenever an event occurs in Javascript, its transmitted to Python which creates a proxy object representing the event, dispatches it, and then sends any DOM changes/etc triggered by the event back to javascript
So in Javascript, every time an event handler is triggered, it sends the event's data over to Python which fabricates a proxy of the event object. The problem is that a single event object in Javascript may trigger numerous listeners as it traverses its bubble chain
Each time an event occurs JS, potentially more than one event object representing it is generated on the python side as a result. I want to eliminate this behaviour
If I create a cache of event objects within Python, I can prevent the default behaviour that is auto-fabricating an event when one is received from Javascript by checking if one has already been cached for the JS counterpart
The problem with this approach is, when do I kill the pythonic copy?
If I don't, that dictionary just continues to grow. What I really need is an OnDeallocate method to fire on the object when it's garbage collected in Javascript, to signal to python to do the same
Anyone knows how to deal with multi click issue? Like every time I click the button it increases by x2
anyone knows how to get cam input from my website into pyopencv ?
i am trying to make a website that makes face filters
Django Question. I'm trying to query the db to get the pk of the current object. I have this:
query_article_object = get_object_or_404(Article, pk=self.kwargs['pk'])
However, this returns
KeyError at /articles/
'pk'
Side note. The following variation produces the same error:
query_article_object = get_object_or_404(Article, id=self.kwargs['pk'])```
Thoughts?
How do I figure out the xpath of an element on Chromium? I'm using selenium.
IIRC you can inspect code (right-click page), find the line, right click and copy xpath
Did that, but all i'm getting is /html/body
Ah....can you select the particular line you want...then right-click. Also, there's the selector tool in the inspect pane. It's an arrow to the top left of the pane
i am trying to make an api with fastapi can i ask questions here?
@cloud harbor I would just go ahead and ask the question. Whether it gets answered comes down to if someone comes by who can answer.
oh ok
i just wanted to know if there is a way to return image url rather than the image itself with the fileresponse
is there a way to upload image as an endpoint
For some reason I'm having a terrible time explaining why I need this this, but, I need a way to detect when an event has finished propagating
Some sort of an 'OnComplete' method on event class
Sorry, this is in Javascript
Any thoughts?
I know that those events are accessable from chrome extensions at least
when you connect to chrome API
it is actually even named in exactly same way I think 😉
https://developer.chrome.com/docs/extensions/reference/
https://developer.chrome.com/docs/extensions/reference/tabs/
onUpdated it is actually, where it is possible to recieve status complete
The complete reference to all APIs made available to Chrome Extensions. This includes APIs for the deprecated Chrome Apps platform as well as APIs still in beta and dev.
Use the chrome.tabs API to interact with the browser's tab system. You can use this API to create, modify, and rearrange tabs in the browser.
perhaps it could of some help
oh!
as example of chrome extension
they provide the next javascript code
document.addEventListener('DOMContentLoaded', function() {
// here I attach my listeners
}
this could be used perhaps without chrome API, it should be available just in JS I think
besides DOMContentLoaded perhaps there other events you can attach yourself to
Hello all have following issue jango rest framework
{
"detail": "Authentication credentials were not provided."
}
This error occurs even though i am passing the correct token in the post request postman
token is passed on the cookie level
i tried to use debug tool of django, i did everything as it is written on django debug tool document
but i don't why i getting this error, please help me 🙂
Is there any workaround?
in settings disable auth
REST_FRAMEWORK = {}
#django
first time seeing this method for enabling debug