I am controlling Raspberry Pi GPIO pins with a python web app. Its work fine in my tests with flask-test-server but its not working from another network or from internet. Raspberry Pi is in a local area network and is visible through the DMZ of the router with port 80 and Apache2 in the internet.I have created with an Apache2 server in raspberry pi and accessing a .py file to change the status of pins. Status of pins are work fine in my tests but its is not working in another network, although it accesses my server from the other network but is not changing the status of GPIO pin. so I know that " if request.method == 'POST'" in "
#app.route('/profile', methods=['GET', 'POST']) " is not working properly in my code but I don't know why ???!!!!
html file:
<!doctype html>
<html lang="en">
<head>
<title>controller</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="{{url_for('static', filename='css/controller.css')}}">
<!--===============================================================================================-->
</head>
<body>
<form method="post">
<span class="switch">
<span class="switch-border1">
<span class="switch-border2">
<input id="switch1" name="checkbox" value="1" type="checkbox"/>
<label for="switch1"></label>
<span class="switch-top"></span>
<span class="switch-shadow"></span>
<span class="switch-handle"></span>
<span class="switch-handle-left"></span>
<span class="switch-handle-right"></span>
<span class="switch-handle-top"></span>
<span class="switch-handle-bottom"></span>
<span class="switch-handle-base"></span>
<span class="switch-led switch-led-green">
<span class="switch-led-border">
<span class="switch-led-light">
<span class="switch-led-glow"></span>
</span>
</span>
</span>
<span class="switch-led switch-led-red">
<span class="switch-led-border">
<span class="switch-led-light">
<span class="switch-led-glow"></span>
</span>
</span>
</span>
</span>
</span>
</span>
<span class="switch">
<span class="switch-border1">
<span class="switch-border2">
<input id="switch2" name="checkbox" value="2" type="checkbox"/>
<label for="switch2"></label>
<span class="switch-top"></span>
<span class="switch-shadow"></span>
<span class="switch-handle"></span>
<span class="switch-handle-left"></span>
<span class="switch-handle-right"></span>
<span class="switch-handle-top"></span>
<span class="switch-handle-bottom"></span>
<span class="switch-handle-base"></span>
<span class="switch-led switch-led-green">
<span class="switch-led-border">
<span class="switch-led-light">
<span class="switch-led-glow"></span>
</span>
</span>
</span>
<span class="switch-led switch-led-red">
<span class="switch-led-border">
<span class="switch-led-light">
<span class="switch-led-glow"></span>
</span>
</span>
</span>
</span>
</span>
</span>
<span class="switch">
<span class="switch-border1">
<span class="switch-border2">
<input id="switch3" name="checkbox" value="3" type="checkbox"/>
<label for="switch3"></label>
<span class="switch-top"></span>
<span class="switch-shadow"></span>
<span class="switch-handle"></span>
<span class="switch-handle-left"></span>
<span class="switch-handle-right"></span>
<span class="switch-handle-top"></span>
<span class="switch-handle-bottom"></span>
<span class="switch-handle-base"></span>
<span class="switch-led switch-led-green">
<span class="switch-led-border">
<span class="switch-led-light">
<span class="switch-led-glow"></span>
</span>
</span>
</span>
<span class="switch-led switch-led-red">
<span class="switch-led-border">
<span class="switch-led-light">
<span class="switch-led-glow"></span>
</span>
</span>
</span>
</span>
</span>
</span>
<input type="submit" value="Apply" style="
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
background-color: white;
color: black;
border: 2px solid #f44336;" />
</form>
</body>
</html>
and py file with flask:
from flask import (
Flask,
g,
redirect,
render_template,
request,
session,
url_for
)
import RPi.GPIO as GPIO
class User:
def __init__(self, identi, username, password):
self.id = identi
self.username = username
self.password = password
def __repr__(self):
return f'<User: {self.username}>'
users = []
mahbod = User(1024, username='xxxxx', password='xxxxx')
mahta = User(1025, username='', password='xxxxxx')
users.append(mahta)
users.append(mahbod)
app = Flask(__name__)
app.secret_key = 'somesecretkeythatonlyishouldknow'
#app.before_request
def before_request():
g.user = None
if 'user_id' in session:
user = [x for x in users if x.id == session['user_id']][0]
g.user = user
#app.route('/login', methods=['GET', 'POST'])
#app.route('/', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session.pop('user_id', None)
username = request.form['username']
pas = request.form['pass']
for x in users:
if x.username == username and x.password == pas:
session['user_id'] = x.id
return redirect(url_for('profile'))
return render_template('login.html')
#app.route('/profile', methods=['GET', 'POST'])
def profile():
if not g.user:
return redirect(url_for('login'))
if request.method == 'POST':
checkbox = request.form.getlist('checkbox')
try:
# set GPIO numbering mode and define output pins
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(20,GPIO.OUT)
GPIO.setup(26,GPIO.OUT)
GPIO.setup(21,GPIO.OUT)
if len(checkbox) == 0:
GPIO.output(21,False)
GPIO.output(20,False)
GPIO.output(26,False)
else:
#for x in checkbox:
if "1" in checkbox:
try:
GPIO.output(21,True)
print("switch_1 on")
except:
pass
else:
try:
GPIO.output(21,False)
print("switch_1 off")
except:
pass
if "2" in checkbox:
try:
GPIO.output(20,True)
print("switch_2 on")
except:
pass
else:
try:
GPIO.output(20,False)
print("switch_2 off")
except:
pass
if "3" in checkbox:
try:
GPIO.output(27,True)
print("switch_4 on")
except:
pass
else:
try:
GPIO.output(27,False)
print("switch_4 off")
except:
pass
except:
return redirect(url_for('not_work'))
return render_template('profile.html')
#app.route('/not_work')
def not_work():
return render_template('not_work.html')
if __name__ == "__main__":
app.run(debug=True)
Related
I'm creating something where my flask backend will get the last added record from mysql, then the frontend will duplicate a div with that new information and display it to the user. It all works fine and as expected, but I don't get how to make it so that the previously duplicated divs contents won't have their values changed when a new record is added.
import copy
import pymysql
from flask import Flask, render_template, request, redirect, url_for, session, jsonify
conn = pymysql.connect(
host = 'localhost',
user = 'root',
password = '',
db = 'panel',
)
cur = conn.cursor()
app = Flask(__name__, template_folder = "templates")
rundupe = 1 # Debug
runpage = True # Debug
#app.route("/")
def index():
return render_template("index.html")
#app.route("/infected", methods=['GET', 'POST'])
def infected():
global rundupe
global runpage
if runpage:
#runpage = False
cur.execute("SELECT id FROM botinfo ORDER BY id DESC LIMIT 1")
res0 = cur.fetchone()[0]
print(res0)
cur.execute("SELECT ip FROM botinfo WHERE id = %s", (res0))
res1 = cur.fetchone()[0]
cur.execute("SELECT os FROM botinfo WHERE id = %s", (res0))
res2 = cur.fetchone()[0]
cur.execute("SELECT country FROM botinfo WHERE id = %s", (res0))
res3 = cur.fetchone()[0]
cur.execute("SELECT date FROM botinfo WHERE id = %s", (res0))
res4 = cur.fetchone()[0]
if res1 and res2 and res3 and res4:
return render_template("infected.html", newip = res1, newos = res2, country = res3, date = res4, id = res0, rundupe = rundupe)
return render_template("infected.html")
#app.route("/payloads")
def payloads():
return render_template("payloads.html")
#app.route("/db")
def database():
return render_template("database.html")
#app.route("/analytics")
def analytics():
return render_template("analytics.html")
#app.route("/cli")
def cli():
return render_template("cli.html")
#app.route("/security")
def security():
return render_template("security.html")
#app.route("/settings")
def settings():
return render_template("settings.html")
#app.route("/accepter", methods=["GET", "POST"])
def accept():
if request.method == "GET":
global rundupe
global runpage
ip = request.args.get("ip")
os = request.args.get("os")
country = request.args.get("country")
date = request.args.get("date")
if ip and os and country and date:
runpage = True
sql = "INSERT INTO botinfo (ip, os, country, date) VALUES (%s, %s, %s, %s)"
cur.execute(sql, (ip, os, country, date))
conn.commit()
rundupe += 1
return render_template("api.html")
app.run("127.0.0.1", 5000, debug = True)
Flask backend, first it gets some information in the accepter route from url parameters and then it saves that information into mysql and sends it to the user in the infected route.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css">
<link href="https://fonts.googleapis.com/css2?family=Chakra+Petch:wght#500&display=swap" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<title>Home</title>
</head>
<body onload="duplicate();" style="background-color: rgb(15, 15, 34);">
<div class="wrapper">
<div class="section">
<div class="top_navbar">
<div class="hamburger">
<a href="#">
<i class="fas fa-bars"></i>
</a>
</div>
</div>
</div>
<div class="sidebar">
<div class="profile">
<span class="icon"><i style="color: white;" class="fas fa-user-tie fa-3x"></i></span>
<h3>Visually</h3>
<p>System Admin</p>
</div>
<ul>
<li>
<a href="/">
<span class="icon"><i class="fas fa-home"></i></span>
<span class="item">Home</span>
</a>
</li>
<li>
<a href="/infected" class="active">
<span class="icon"><i class="fas fa-desktop"></i></span>
<span class="item">Infected</span>
</a>
</li>
<li>
<a href="/payloads">
<span class="icon"><i class="fas fa-scroll"></i></span>
<span class="item">Payloads</span>
</a>
</li>
<li>
<a href="/db">
<span class="icon"><i class="fas fa-database"></i></span>
<span class="item">Database</span>
</a>
</li>
<li>
<a href="/analytics">
<span class="icon"><i class="fas fa-chart-line"></i></span>
<span class="item">Analytics</span>
</a>
</li>
<li>
<a href="/cli">
<span class="icon"><i class="fas fa-terminal"></i></span>
<span class="item">Web CLI</span>
</a>
</li>
<li>
<a href="/security">
<span class="icon"><i class="fas fa-user-shield"></i></span>
<span class="item">Security</span>
</a>
</li>
<li>
<a href="/settings">
<span class="icon"><i class="fas fa-cog"></i></span>
<span class="item">Settings</span>
</a>
</li>
</ul>
</div>
</div>
<h1 style="text-align: center; color: white; margin-top: 2%; font-size: 50px;">Infected Machines</h1>
<div class="statsBox" style="margin-left: 415px; margin-top: 90px; width: 800px; height: 400px; overflow-y: auto;" id="machines">
<p style="text-align: center; font-size: 20px">Machines</p>
<div class="infectedBox" id="infectedBox" style="width: 793px; height: 90px; margin-top: 15px; cursor: pointer; background-color: rgb(2, 2, 31); display: none;">
<script type="text/javascript">
let i = 0;
let id = 0;
let num = 0;
const og = document.getElementById('infectedBox');
function duplicate() {
if('{{ rundupe }}') {
for(let i = 0; i < '{{ rundupe }}'; ++i) {
let clone = og.cloneNode(true);
clone.style.display = 'block';
clone.id = "duplicater" + ++i;
og.parentNode.appendChild(clone);
++num;
++id;
const number = document.querySelector(`#duplicater${i} #number`).textContent = `#${num}`;
const mainInfo = document.querySelector(`#duplicater${i} #mainInfo`).textContent = `Country: {{ country }}, OS: {{ newos }}, Date Captured: {{ date }}`;
const botInfo = document.querySelector(`#duplicater${i} #botInfo`).textContent = `Bot: {{ newip }}`;
console.log(number, mainInfo, botInfo);
}
}
}
</script>
<span class="icon"><i style="margin-left: 10px; margin-top: 12px;" class="fas fa-user fa-4x"></i></span>
<p id="botInfo" style="color: white; margin-top: -70px; margin-left: 100px; font-size: 20px;"></p>
<p id="mainInfo" style="color: white; margin-top: 12px; margin-left: 100px;"></p>
<p id="number" style="color: white; margin-top: -60px; margin-left: 700px; font-size: 60px;">#<script type="text/javascript">document.write(num);</script></p>
</div>
</div>
<script type="text/javascript">
let hamburger = document.querySelector(".hamburger");
hamburger.addEventListener("click", () => {
document.querySelector("body").classList.toggle("active");
})
</script>
</body>
</html>
html page to display the info.
from urllib.request import urlopen
from datetime import date
import urllib.request
import requests
import platform
import json
import sys
import re
today = date.today()
d1 = today.strftime("%m/%d/%Y")
url = 'http://ipinfo.io/json'
response = urlopen(url)
data = json.load(response)
country = data['country']
print(country)
pubip = urllib.request.urlopen('https://ident.me').read().decode('utf8')
print(pubip)
os = platform.system()
print(os)
requests.get(f"http://127.0.0.1:5000/accepter?ip={pubip}&os={os}&country={country}&date={d1}")
Script that makes GET request to server.
I don't understand how to get the div to duplicate in such a way that the value of the old one isn't altered, and only the new one uses the value of what my flask route is returning.
I am attempting to scrape a site for for some data on an long list of items. Below is my code:
def find_info():
page = requests.get(URL)
soup = bs(page.content, 'html.parser')
soup2 = bs(soup.prettify(), "html.parser")
lists = soup2.find_all('div', class_="featured_item")
#with open('data.csv', 'w', encoding='utf8', newline='') as f:
# thewriter = writer(f)
# header = ['Rank', 'Number', 'Price'] #csv: comma separated values
# thewriter.writerow(header)
for list in lists:
stats = lists.find_all('div', class_="item_stats")
sale = lists.find('div', class_="sale")
rank = float(stats.select('.item_stats span')[0].text)
number = stats.select('.item_stats span')[1].text.strip().replace('#', '')
price = sale.select('span')[0].text.strip().replace('◎', '')
print(rank, number, price)
find_info()
I get the following error:
Traceback (most recent call last):
File "C:\Users\Cameron Lemon\source\repos\ScrapperGUI\module1.py", line 36, in <module>
find_info()
File "C:\Users\Cameron Lemon\source\repos\ScrapperGUI\module1.py", line 27, in
find_info
stats = lists.find_all('div', class_="item_stats")
File "C:\Users\Cameron Lemon\AppData\Local\Programs\Python\Python310\lib\site-
packages\bs4\element.py", line 2253, in __getattr__
raise AttributeError(
AttributeError: ResultSet object has no attribute 'find_all'. You're probably treating a
list of elements like a single element. Did you call find_all() when you meant to call
find()?
Press any key to continue . . .
This code runs well, until I add the line for list in lists: and use find_all() instead of find(). I am very confused, because in the past I have coded to find data for the first item in the list successfully and then set a for loop and changed my find() to find_all(). Any advice is much appreciated. Thank you
Below is my lists variable, for two of the many items within it.
[<div class="featured_item">
<div class="featured_item_img">
<a href="/degds/3251/">
<img src="URL"/>
</a>
</div>
<div class="featured_image_desc" style="padding-bottom: 5px;">
<div class="item_stats">
<div class="item_stat">
rank
<span>
1
</span>
</div>
<div class="item_stat">
item no.
<span>
#3251
</span>
</div>
</div>
<div class="sale" style="height: 40px; margin-top: 10px; margin-bottom: 10px;">
<span>
not for sale
</span>
</div>
<div class="last_sale" style="font-size: 11px;">
no sale history
</div>
</div>
</div>, <div class="featured_item">
<div class="featured_item_img">
<a href="/dgds/8628/">
<img src="URL"/>
</a>
</div>
<div class="featured_image_desc" style="padding-bottom: 5px;">
<div class="item_stats">
<div class="item_stat">
rank
<span>
2
</span>
</div>
<div class="item_stat">
item no.
<span>
#8628
</span>
</div>
</div>
<div class="sale" style="height: 40px; margin-top: 10px; margin-bottom: 10px;">
<span>
not for sale
</span>
</div>
<div class="last_sale" style="font-size: 11px;">
no sale history
</div>
</div>
You are using find_all method two times. When you use for loop then you will get each item meaning list didn't exist any more. So we can't use find_all without list that's why you are getting that error.
html='''
<div class="featured_item">
<div class="featured_item_img">
<a href="/degds/3251/">
<img src="URL"/>
</a>
</div>
<div class="featured_image_desc" style="padding-bottom: 5px;">
<div class="item_stats">
<div class="item_stat">
rank
<span>
1
</span>
</div>
<div class="item_stat">
item no.
<span>
#3251
</span>
</div>
</div>
<div class="sale" style="height: 40px; margin-top: 10px; margin-bottom: 10px;">
<span>
not for sale
</span>
</div>
<div class="last_sale" style="font-size: 11px;">
no sale history
</div>
</div>
</div>, <div class="featured_item">
<div class="featured_item_img">
<a href="/dgds/8628/">
<img src="URL"/>
</a>
</div>
<div class="featured_image_desc" style="padding-bottom: 5px;">
<div class="item_stats">
<div class="item_stat">
rank
<span>
2
</span>
</div>
<div class="item_stat">
item no.
<span>
#8628
</span>
</div>
</div>
<div class="sale" style="height: 40px; margin-top: 10px; margin-bottom: 10px;">
<span>
not for sale
</span>
</div>
<div class="last_sale" style="font-size: 11px;">
no sale history
</div>
</div>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html,"html.parser")
lists = soup.find_all('div', class_="featured_item")
for lis in lists:
stats = lis.find('div', class_="item_stats")
sale = lis.find('div', class_="sale")
rank = float(stats.select('.item_stats span')[0].text)
number = stats.select('.item_stats span')[1].text.strip().replace('#', '')
price = sale.select('span')[0].text.strip().replace('◎', '')
print(rank, number, price)
Output:
1.0 3251 not for sale
2.0 8628 not for sale
The error is raised :
Page not found (404) No cart matches the given query.
Request Method: GET Request
URL: http://127.0.0.1:8000/change_quan?cid=1&quantity=2
Raised by: myapp.views.change_quan
when i am trying to save quantity value in database
i tried but this error raised always
my views.py
def productcart(request):
context = {}
items = cart.objects.filter(user__id=request.user.id,status=False)
context["items"] = items
if request.user.is_authenticated:
if request.method=="POST":
pid = request.POST["pid"]
qty = request.POST["qty"]
img = request.POST["img"]
dis_price = request.POST["dis_price"]
is_exist = cart.objects.filter(product__id=pid,user__id=request.user.id,status=False)
if len(is_exist)>0:
context["msg"] = "item already exist in cart"
context["cls"] = "alert alert-warning"
else:
product = get_object_or_404(Product,id=pid)
usr = get_object_or_404(User,id=request.user.id)
c = cart(user=usr,product=product,quantity=qty,image=img,total_price=dis_price)
c.save()
context["msg"] = "{} Added in cart".format(product.name)
context["cls"] = "alert alert-success"
else:
context["status"] = "Please login first to add products to cart"
return render(request,'E-commerce-cart.html',context)
def get_cart_data(request):
items = cart.objects.filter(user__id=request.user.id,status=False)
sale,total,quantity=0,0,0
for i in items:
sale+=i.product.discount
total+=i.product.price
quantity+=i.quantity
res={
"total":total,"offer":sale,"quan":quantity
}
return JsonResponse(res)
def change_quan(request):
qty = request.GET["quantity"]
cid = request.GET["cid"]
print(request.GET)
cart_obj = get_object_or_404(cart,id=cid)
cart_obj.quantity = qty
cart_obj.save()
return HttpResponse(1)
my urls.py
"""emarket URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from os import name
from django.contrib import admin
from django.urls import path
from myapp import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.home,name='home'),
path('shop/',views.shop,name='shop'),
path('login/',views.create_user,name='login'),
path('logout/',views.user_logout,name='logout'),
path('cart/',views.productcart,name='cart'),
path('checkout/',views.checkout,name='checkout'),
path('product_detail/',views.product_detail,name='prodct-detail'),
path('find_us/',views.find_us,name='find'),
path('blog/',views.blog,name='blog'),
path('base/',views.base),
path('api/categories',views.all_categories,name="all_categories"),
path('api/brand',views.brand,name="brand"),
path('api/products',views.product_filter_api,name="product_filter_api"),
path('user_check/',views.check_user,name="check_user"),
path('filter_product/',views.filter_product,name="filter_product"),
path('add_to_favourite/',views.add_to_favourite,name="add_to_favourite"),
path('all_favourites/',views.all_favourites,name="all_favourites"),
path('forgotpass',views.forgotpass,name="forgotpass"),
path('resetpass',views.resetpass,name="resetpass"),
path('get_cart_data',views.get_cart_data,name="get_cart_data"),
path('change_quan',views.change_quan,name='change_quan'),
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
my models.py
class cart(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
product = models.ForeignKey(Product,on_delete=models.CASCADE)
image = models.ImageField(default=False)
total_price=models.FloatField(default=False)
quantity = models.IntegerField()
status = models.BooleanField(default=False)
added_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
def __str__(self):
return self.user.username
my html code
{% extends 'base.html' %}
{% block head %}
<style>
.k{height: 1px;background-color: rgb(211, 207, 207);}
.s{color:rgb(240, 240, 240);
letter-spacing: 3px;
font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
font-weight: 400;}
.cncl_icn{
float: left;
margin: 15px;
padding-top: 10px;
}
.a:hover{
background-color:rgba(152, 209, 255, 0.705);color: rgb(255, 255, 255);box-shadow:0px 0px 7px 7px rgba(204, 201, 201, 0.5) ;
}
#media screen and (max-width:680px){
.b{opacity: 0;}
/* .v{position: absolute;top: 5px;} */
.s{font-size: 15px;}
}
#media screen and (min-width:1024px){
.s{font-size: 20px;}
}
</style>
{% endblock %}
{% block body %}
{% if user.is_superuser %}
<div class="container-fluid "></div>
<h1 class="jumbotron my-5" >you are not Allowed here</h1>
{% else %}
{% if status %}
<h1 class="jumbotron my-5">{{status}}</h1>
{% else %}
{% if msg %}
<div class="{{cls}}">{{msg}}</div>
{% endif %}
<div class="row v " style="margin-right: 0%;">
<div class="col-lg-7" >
<div class="row text-center p-3 b" style="background-color: rgba(2, 184, 184, 0.863); background-attachment: fixed;">
<div class="col-md-3 "> <h3 class="s">Product</h3></div>
<div class="col-md-3 "><h3 class="s">Price</h3></div>
<div class="col-md-3 "><h3 class="s">Qantity</h3></div>
<div class="col-md-3 "><h3 class="s">Total</h3></div>
</div>
{% for i in items %}
<div class="row a border-bottom" id="col{{i.product.id}}">
<div class="col-md-3 text-center " >
<i class="far fa-times-circle cncl_icn" id="cross{{i.product.id}}" style="font-size: 30px;"></i>
<img class="mt-4" src="/media/{{i.image}}" alt="check ur internet!" height="150px">
<h4 class="ml-5" style="color: black;">{{i.product.name}}</h4>
<p class="ml-5">Size:{{i.product.size}} , color:{{i.product.color}}</p>
</div>
<div class="col-md-3 text-center mt-5">
{%if i.total_price < i.product.price%}
<del style="font-weight: bold; color: grey;" >${{i.product.price}}</del> $<p class="d-inline" style="font-weight: bold;" id="price{{i.product.id}}">{{i.total_price}}</p>
{% else %}
$<p class="d-inline" style="font-weight: bold;" id="price{{i.product.id}}">{{i.product.price}}</p>
{% endif %}
</div>
<div class="col-md-3 text-center">
<div class="form-group mt-4">
<div class="input-group">
<div class="input-group-btn ">
<button id="down" class="btn btn-default" onclick="change_quan('{{i.product.id}}','minus')" style="font-size: 25px;background: none;border: none;font-weight: bold;">-</button>
</div>
<input type="number" id="cart{{i.product.id}}" class="form-control text-center pt-3" value="{{i.quantity}}" style="width: 30px;border: none;font-weight: bold;background: none;">
<div class="input-group-btn">
<button id="up" class="btn btn-default" onclick="change_quan('{{i.product.id}}','plus')" style="font-size: 25px;background: none;border: none;font-weight: bold;">+</button>
</div>
</div>
</div>
</div>
<div class="col-md-3 mt-5 text-center">
{%if i.total_price < i.product.price %}
$<p class="d-inline" style="font-weight: bold;" id="total{{i.product.id}}">{{i.total_price}}</p>
{% else %}
$<p class="d-inline" style="font-weight: bold;" id="total{{i.product.id}}">{{i.product.price}}</p>
{% endif %}
</div>
</div>
<script>
$(function() {
$("#cross{{i.product.id}}").hover(function() {
$("#cross{{i.product.id}}").toggleClass("fas fa-times-circle").toggleClass("far fa-times-circle")
})
// to remove product from cart
$("#cross{{i.product.id}}").confirm({
title: 'Confirm',
content: 'Are you sure to remove this product from cart',
theme: 'modern',
buttons:{
confirm: function() {
$('#col{{i.product.id}}').remove()
},
cancel: function (){}
}
})
})
</script>
{% endfor %}
</div>
<script>
function grandTotal(){
$.ajax({
url:"{% url 'get_cart_data' %}",
type:'get',
success:function(data){
p = Math.round((data.offer/data.total)*100,2)
$('.item_total').html("$"+data.total)
$('#offer').html("$"+data.offer)
$('#per').html("("+p+"%)")
$('#quantity').html(data.quan)
c = (data.total)-(data.offer)
$('#grand_Total').html("$"+c)
}
})
}
grandTotal()
function change_quan(id,action){
let old = $("#cart"+id).val();
quan = 0
if(action=="plus"){
quan+=parseInt(old)+1
$('#total'+id).text( parseFloat($('#total'+id).text()) + parseFloat($('#price'+id).text()))
}
else{
quan+=parseInt(old)-1
$('#total'+id).text( parseFloat($('#total'+id).text()) - parseFloat($('#price'+id).text()))
}
$("#cart"+id).val(quan);
$.ajax({
url:"{% url 'change_quan' %}",
type:"get",
data:{cid:id,quantity:quan},
success:function(data){
alert(data)
}
});
}
</script>
<div class="col-md-5 text-center py-5" style="background-color: rgba(255, 176, 218, 0.397);">
<div id="cartt"></div>
<div class="row">
<img src="/static/Images/estore1.png" alt="" height="300px" style="margin: auto;">
</div>
<div class="pb-3 " style="font-size:30px;font-weight: bold;">--------------------</div>
<h4 class="pt-3" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">Total: <span style="font-size: 28px;" class="item_total"></span></h4>
<h4 class="pt-1" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">Quantity: <span style="font-size: 28px;" id="quantity"></span><span style="text-transform: none;"> Items</span></h4>
<h4 class="pt-1" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">You Saved: <span style="font-size: 28px;" id="offer"></span><span class='text-success'style="font-size: 20px;" id="per"></span></h4>
<h4 class="py-1" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">Grand Total: <del style="font-size: 25px; color:grey;" class="item_total"></del><span style="font-size: 28px;" id="grand_Total"></span></h4>
<h4 class="pt-3">Shipping charges will calculated at checkout</h4>
<form class="pt-3" action="" >
<!-- <input type="text" placeholder="Coupon code.." name="cod" class="mt-3 text-center" style="letter-spacing: 2px;font-size: 20px;border-radius: 25px;width: 250px;height: 47px;background-color: rgb(255, 255, 255);border:2px solid thistle;" >
<input type="submit" class="mt-3" value="Apply Code"name="acd" style="letter-spacing: 2px;font-size: 25px;border-radius: 25px;border: none;width: 250px;height: 45px;background-color: rgb(161, 158, 158);color: rgb(255, 255, 255);" > -->
<input type="submit" value="CHECKOUT" name="che" class="mt-5" style="letter-spacing: 2px;font-size: 25px;border-radius: 25px;border: none;width: 250px;height: 45px;background-color: black;color: rgb(255, 255, 255);" >
</form>
</div>
</div>
{% endif %}
</div>
{% endif %}
{% endblock %}
if data does not exist 'get_object_or_404' will throw 404 error, As per your request You are trying to retrieve data with primary key 1, but data is not available
That’s why you get this error. so please check you table or try with other pk value
def change_quan(request):
qty = request.GET["quantity"]
cid = request.GET["cid"]
print(request.GET)
cart_obj = get_object_or_404(cart,id=cid) # please check this cid value
cart_obj.quantity = qty
cart_obj.save()
return HttpResponse(1)
get_object_or_404 is not the correct choice here. Since object with id=cid was not found in database, 404 error was raised. This is the expected behaviour of get_object_or_404.
Did you mean to use get_or_create object incase the object that is trying to be fetched from database is not found?
I have 3 apps in django project, I created a new html file on dictionary app which is Refcode_Info.html. This page must render a simple form and linked a simple. When I click the button, form must show on screen. However when I click the button, I get 404 page and mixxed url, Likewise, I want to direct another url on this page, but seconda url already exits in this project and I have used on different stages on project but doesnt work on new html page(Refcode_Info.html). My new html may have a problems but my Accounts links is working on different stages.
This is my Refcode_Info.html codes on below.
<script>
$(document).ready(function() {
if ($(document).width() > 768) {
$("#accordion_desktop").accordion({
header: '.header',
collapsible: true,
active: false,
autoHeight: true,
heightStyle: 'content',
animate: 50
});
$("#desktop").show();
} else {
$("#accordion_mobile").accordion({
header: '.header',
collapsible: true,
active: false,
autoHeight: true,
heightStyle: 'content',
animate: 50
});
$("#mobile").show();
}
$(window).resize(function() {
if ($(document).width() > 768) {
$("#accordion_desktop").accordion({
header: '.header',
collapsible: true,
active: false,
autoHeight: true,
heightStyle: 'content',
animate: 50
});
$("#desktop").show();
$("#mobile").hide();
} else {
$("#accordion_mobile").accordion({
header: '.header',
collapsible: true,
active: false,
autoHeight: true,
heightStyle: 'content',
animate: 50
});
$("#mobile").show();
$("#desktop").hide();
}
});
});
</script>
<style>
.ui-widget-content {
border: none;
}
.ui-state-focus {
outline: none;
}
.sign-container {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
/* add */
justify-content: center;
/* add to align horizontal */
align-items: center;
/* add to align vertical */
}
#accordion_desktop .ui-icon {
display: none;
}
#accordion_desktop .ui-accordion-header a {
padding-left: 0;
}
#accordion_mobile .ui-icon {
display: none;
}
#accordion_mobile .ui-accordion-header a {
padding-left: 0;
}
</style>
<div id="desktop" class="container-fluid p-0" style="display:none; text-align:center;">
<div id="accordion_desktop">
<!-- Not a student-->
<div class="header m-0 p-0" style="border:none; background: #0c151D;">
<div class="row pt-5 pb-4 m-0" style="background-color: #0c151D; padding-top: 1rem !important; padding-bottom: 1rem !important;">
<div class="col-4 col-md-2 p-0">
<div class="text-right">
<img class="img-fluid" src="/static/img/studentnot.png" style="max-height: 100px;" />
</div>
</div>
<div class="col-8 col-md-10 text-center">
<p style="color:#FFFFFF; font-size:1.4em;padding-top:1.25em;">Üniversite personeli/öğrencisi değilim <img class="img-fluid" src="/static/img/plus_blue.png" style="max-height: 25px; margin-bottom: 5px; margin-left: 10px;" /></p>
</div>
</div>
</div>
<div class="row pt-4 pb-4" style="background-color:#0c151D;">
<div class="col-12 col-md-12 text-center pt-3">
<p style="color:#FFFFFF; font-size:1.2em;">Legaling'in zengin veri tabanından, şu aşamada yalnızca üniversiteler vasıtasıyla faydalanılabilmektedir. Ancak istisnai durumlarda bireysel kullanıcılara da ücretsiz erişim hakkı tanımlanabilmektedir. Bu kapsamda Legaling'i nereden duyduğunuz
ve neden tam bir erişim talep ettiğinizi bizimle paylaşırsanız başvurunuzu değerlendirmeye almaktan mutluluk duyarız.</p>
<a class="btn btn-primary" href="{% url 'Accounts:personalize' %}">Referans Kodu Ekle</a>
<a class="btn btn-primary" href="mailto:legalingnetdestek#gmail.com">Kod Talebi Gönder</a>
<a class="btn btn-primary" href="mailto:legalingnetdestek#gmail.com">Konu ile İlgili Düşünceleriniz</a>
</div>
</div>
<!-- Student -->
<div class="header m-0 p-0" style="border:none; background: #1E2329;">
<div class="row pt-5 pb-4 m-0" style="background-color:#1E2329; padding-top: 1rem !important; padding-bottom: 1rem !important;">
<div class="col-4 col-md-2 p-0">
<div class="text-right">
<img class="img-fluid" src="/static/img/student.png" style="max-height: 100px;" />
</div>
</div>
<div class="col-8 col-md-10 text-center">
<p style="color:#FFFFFF; font-size:1.4em;padding-top:1.25em;">Üniversite personeliyim/öğrencisiyim. <img class="img-fluid" src="/static/img/plus_gray.png" style="max-height: 25px; margin-bottom: 5px; margin-left: 10px;" /></p>
</div>
</div>
</div>
<div class="row pt-4 pb-4" style="background-color:#1E2329;">
<div class="col-12 col-md-12 text-center pt-3">
<p style="color:#FFFFFF; font-size:1.2em;">Legaling, belirli bir üniversiteden en az 2 personel ya da 10 öğrenciden talep gelmesi durumunda ilgili üniversite ile Legaling'in zengin veri tabanını açmak üzere temasa geçer. Bu doğrultuda Legaling'in üniversiteniz ile temasa geçmesini
istiyorsanız aşağıdaki alanları doldurunuz</p>
<a class="btn btn-primary" href="{% url 'Dictionary:getUniInfo' %}">Üniversite Bilgilerini Paylaş</a>
</div>
</div>
</div>
</div>
<!-- MOBILE -->
<div id="mobile" class="container-fluid p-0" style="display:none;">
<div id="accordion_mobile">
<!-- Not a Student -->
<div class="header m-0 p-0" style="border:none; background: #0c151D;">
<div class="row m-0 p-1" style="background-color:#0C151D; padding-top: 1rem !important; padding-bottom: 1rem !important;">
<div class="col-3 col-md-2 p-0">
<div class="sign-container text-right">
<img class="img-fluid" src="/static/img/studentnot.png" style="max-height: 60px;" />
</div>
</div>
<div class="col-8 col-md-9 text-center">
<p style="color:#FFFFFF; font-size:1.2em;">Legaling'in zengin veri tabanından, şu aşamada yalnızca üniversiteler vasıtasıyla faydalanılabilmektedir. Ancak istisnai durumlarda bireysel kullanıcılara da ücretsiz erişim hakkı tanımlanabilmektedir. Bu kapsamda Legaling'i nereden
duyduğunuz ve neden tam bir erişim talep ettiğinizi bizimle paylaşırsanız başvurunuzu değerlendirmeye almaktan mutluluk duyarız.</p>
</div>
<div class="col-1 col-md-1 p-0">
<div class="sign-container">
<img class="img-fluid" src="/static/img/plus_blue.png" style="max-height: 25px;" />
</div>
</div>
</div>
</div>
<!-- Student -->
<div class="header m-0 p-0" style="border:none; background: #1E2329;">
<div class="row p-1 m-0" style="background-color:#1E2329; padding-top: 1rem !important; padding-bottom: 1rem !important;">
<div class="col-3 col-md-2 p-0">
<div class="sign-container text-right">
<img class="img-fluid" src="/static/img/student.png" style="max-height: 60px;" />
</div>
</div>
<div class="col-8 col-md-9 text-center">
<p style="color:#FFFFFF; font-size:1.2em; padding-top: 1em;">Üniversite personeliyim/öğrencisiyim.</p>
</div>
<div class="col-1 col-md-1 p-0">
<div class="sign-container">
<img class="img-fluid" src="/static/img/plus_gray.png" style="max-height: 25px;" />
</div>
</div>
</div>
</div>
<div class="row pt-4 pb-4" style="background-color:#1E2329;">
<div class="col-12 col-md-12 text-center pt-3">
<p style="color:#FFFFFF; font-size:1.2em;">Legaling, belirli bir üniversiteden en az 2 personel ya da 10 öğrenciden talep gelmesi durumunda ilgili üniversite ile Legaling'in zengin veri tabanını açmak üzere temasa geçer. Bu doğrultuda Legaling'in üniversiteniz ile temasa geçmesini
istiyorsanız aşağıdaki alanları doldurunuz</p>
</div>
</div>
</div>
</div>
This is views.py page attached below;
def getUniInfo(request):
text = open(os.path.join(settings.BASE_DIR, "Dictionary", "templates","Refcode_Info.html"),"r",encoding="utf8")
UsageText = text.read()
text.close()
if request.method == 'POST':
form = askUniversityInfoForm(request.POST)
if form.is_valid():
obj = UserUniversity() # get new user details
obj.university = form.cleaned_data['universityName']
obj.university_user_email = form.cleaned_data['universityEmail']
obj.save()
mail_subject = "Legaling Aktivasyon Maili"
to_email = form.cleaned_data.get('email')
email = EmailMessage(mail_subject, message, to=[to_email])
email.content_subtype = "html"
email.send()
context = {'UserUniversity', UserUniversity}
return render(request, "Refcode_Info.html", context)
else:
return redirect('Dictionary:index')
else:
form = askUniversityInfoForm()
if(request.is_ajax()):
return render(request, 'usertext_partial.html', {'title':"Neden Referans Kodu Almalıyım?", 'text':UsageText})
else:
return render(request, 'usertext.html', {'title':"Neden Referans Kodu Almalıyım?", 'text':UsageText})
This is forms.py attached below;
class askUniversityInfoForm(forms.Form):
universityName= forms.CharField(label='Your University Name', max_length=100, required=True, widget=forms.TextInput())
universityEmail= forms.CharField(label='Your university Email Address', max_length=100, required=True, widget=forms.TextInput())
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('Gönder', 'Gönder', css_class='bbtn btn-block btn-success'))
super(askUniversityInfoForm, self).__init__(*args, **kwargs)
if not 'userid' in self.initial:
self.fields['name'] = forms.CharField(required=True, label="Adınız", max_length=50)
self.fields['surname'] = forms.CharField(required=True, label="Soyadınız", max_length=100)
self.fields['email'] = forms.EmailField(required=True, label="E-Posta Adresiniz", max_length=150)
self.fields['phonenumber'] = forms.RegexField(regex=r'^\([0-9]{3}\)\-?\s?[0-9]{3}\-?\s?[0-9]{2}\-?\s?[0-9]{2}$',required=False,label='Cep Telefonu Numarası', widget=forms.widgets.TextInput(attrs={'type':'tel','class':'input-phone','onfocus':'registerphoneinput();'}), error_messages = {'invalid':"Telefon Numarası Formatı Doğru Değil"})
self.fields['profession'] = ProfessionchoiceField(queryset=Profession.objects.all(), required=True,label='Mesleğiniz')
self.fields['captcha'] = ReCaptchaField(widget=ReCaptchaV2Checkbox, label='')
Also the my urls;
from django.conf.urls import url, include
from django.urls import path, re_path
from Dictionary import views
path('referencecodetext', views.referencecodetext, name='referencecodetext'),
path('getUniInfo', views.getUniInfo, name='getUniInfo'),
Also, I have url output like this, I research which is why but I couldn't found it.
enter image description here
Anyone have a idea?
names = []
for code in soup.find_all('li'):
a_tag = code.find("a")
if a_tag is not None and 'title' in a_tag.attrs:
l = a_tag.get('title')
names.append(l)
time.sleep(1)
print(names)
When I run the script, it returns only a few names (e.g. title attributes) out of 30 or so and all tags contain the title attribute.
Thank you!
Here's the html code for the one that worked:
<li class="wo9IH">
<div class="uu6c_">
<div class="t2ksc">
<div class="RR-M- h5uC0 SAvC5" role="button" tabindex="0">
<canvas class="CfWVH" height="40" width="40" style="position: absolute; top: -5px; left: -5px; width: 40px; height: 40px;"></canvas>
<span class="_2dbep " role="link" tabindex="0" style="width: 30px; height: 30px;"><img alt="damla_dx's profile picture" class="_6q-tv" src="https://scontent-hbe1-1.cdninstagram.com/v/t51.2885-19/s150x150/100947324_584513555780923_3392957389983449088_n.jpg?_nc_ht=scontent-hbe1-1.cdninstagram.com&_nc_ohc=cpbHm-9Tg24AX-Y5ZTo&oh=523572e76dc634c387c1bce8f5ee24fd&oe=5EF8F269"></span>
</div>
<div class="enpQJ">
<div class="d7ByH"><a class="FPmhX notranslate _0imsa " title="damla_dx" href="/damla_dx/">damla_dx</a></div>
<div class="wFPL8 ">𝒟𝒶𝓂𝓁𝒶</div>
</div>
</div>
<div class="Pkbci"><button class="sqdOP L3NKy y3zKF " type="button">Follow</button></div>
</div>
</li>
and here's the code for the one that didn't:
<li class="wo9IH">
<div class="uu6c_">
<div class="t2ksc">
<div class="RR-M- SAvC5" role="button" tabindex="0">
<canvas class="CfWVH" height="40" width="40" style="position: absolute; top: -5px; left: -5px; width: 40px; height: 40px;"></canvas>
<a class="_2dbep qNELH kIKUG" href="/connie_mario/" style="width: 30px; height: 30px;"><img alt="connie_mario's profile picture" class="_6q-tv" src="https://scontent-hbe1-1.cdninstagram.com/v/t51.2885-19/s150x150/25016555_1962725540720404_7523275851970904064_n.jpg?_nc_ht=scontent-hbe1-1.cdninstagram.com&_nc_ohc=AvK0clN2PSMAX-detNw&oh=6184a0c465a9bfcd04617d134cde4fe9&oe=5EFA793D"></a>
</div>
<div class="enpQJ">
<div class="d7ByH"><a class="FPmhX notranslate _0imsa " title="connie_mario" href="/connie_mario/">connie_mario</a></div>
<div class="wFPL8 ">👑Connie_ Mario👑</div>
</div>
</div>
<div class="Pkbci"><button class="sqdOP L3NKy y3zKF " type="button">Follow</button></div>
</div>
</li>
You can do something simpler with css selctors:
for artist in code.select('a[title]'):
print(artist.text)
For the two snippets in your question, the output should be:
connie_mario
damla_dx