How to get the table details based on post request django - python-3.x

**views.py**
[if request.method == "POST":
from_date = request.POST.get("from_date")
print(from_date)
to_date = request.POST.get("to_date")
print(to_date)
get_date_from_dates = Scrapper.objects.all().filter(created_at=from_date, updated_at=to_date)
print(len(get_date_from_dates))
page = request.GET.get('page', 1)
paginator = Paginator(get_date_from_dates, 5)
global users
try:
users = paginator.page(page)
except PageNotAnInteger:
users = paginator.page(1)
except EmptyPage:
users = paginator.page(paginator.num_pages)
else:
user_list = Scrapper.objects.all()
page = request.GET.get('page', 1)
paginator = Paginator(user_list, 5)
try:
users = paginator.page(page)
except PageNotAnInteger:
users = paginator.page(1)
except EmptyPage:
users = paginator.page(paginator.num_pages)
return render(request, "home.html", { 'users': users })
return render(request, "home.html", {'users': users})][1]
**home.html**
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<body>
<style>
h2 {text-align: center;}
</style>
<h1>Facilgo Completed Jobs</h1>
<form action="" method="post">
{% csrf_token %}
<label for="from_date">From Date:</label>
<input type="date" id="from_date" name="from_date">
<label for="to_date">To Date:</label>
<input type="date" id="to_date" name="to_date">
<input type="submit"><br>
</form>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Summary Details</h2>
<table id="bootstrapdatatable" class="table table-striped table-bordered" width="100%">
<thead>
<tr>
<th>user_registration_source_id</th>
<th>user_type</th>
<th>user_id</th>
<th>source</th>
<th>source_url</th>
<th>created at</th>
<th>updated at</th>
</tr>
</thead>
<tbody>
{% for stud in users %}
{% csrf_token %}
<tr>
<td>{{stud.user_registration_source_id}}</td>
<td>{{stud.user_type}}</td>
<td>{{stud.user_id}}</td>
<td>{{stud.source}}</td>
<td>{{stud.source_url}}</td>
<td>{{stud.created_at}}</td>
<td>{{stud.updated_at}}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% if users.has_other_pages %}
<ul class="pagination">
{% if users.has_previous %}
<li>«</li>
{% else %}
<li class="disabled"><span>«</span></li>
{% endif %}
{% if user.number|add:'-4' > 1 %}
<li>…</li>
{% endif %}
{% for i in users.paginator.page_range %}
{% if users.number == i %}
<li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
{% elif i > users.number|add:'-5' and i < users.number|add:'5' %}
<li>{{ i }}</li>
{% endif %}
{% endfor %}
{% if users.has_next %}
<li>»</li>
{% else %}
<li class="disabled"><span>»</span></li>
{% endif %}
</ul>
{% endif %}
</div>
</div>
</div>
</body>
</html>
Webpage
When I post my from date and to date it would check the "created at" and "updated at" field in table and able to view only the datas of particular date. I have written the post request and get the from date and to date from the form. Is there any solution after posting data only get the values of particular dates in table. But at the opening the webpage it should show all datas in table
Output:
Output Image

I think its better approach to use a certain time period if not chosen by the user. for example one month range.
from datetime import date as dt
from dateutil.relativedelta import relativedelta
if request.method == "POST":
if "from_date" and "to_date" in request.POST:
from_date = request.POST.get("from_date")
to_date = request.POST.get("to_date")
else:
from_date = dt.today()
to_date = today + relativedelta(months=+1)
and then filter with this dates.

Related

Django NoReverseMatch Error on Update and Delete Buttons

Thank you for reading my question, and for your help.
I wrote a simple CRUD app, and used django-tables2 module to make my tables look pretty and more robust. I am using django 3.2, python 3.8.5, django_tables2 2.3.4.
I can enter a query in the search bar on the home.html page and lists the returned results from a postgresql on the search_results.html page. On the search_results page, I have buttons next to each returned row with edit and delete options, when I hover over update buttons it points to url for localhost:8955/update/7887 or localhost:8955/delete/7887 for the delete button, of course the last four digits are unique to the returned rows, however when I click on the update or delete button I get a NoReverseMatch error. I am at my wits end what is causing the edit and delete buttons not to work, your help and assistance is very much appreciated it.
Image with the returned results with the update and delete button
tables.py
from .models import EsgDatabase
from django.urls import reverse_lazy
from django.contrib.auth.models import User as user
class EsgListViewTable(tables.Table):
class Meta:
model = EsgDatabase
template_name = "django_tables2/bootstrap-responsive.html"
fields = ('id','role', 'hq','system','market','state','zone','arrisseachangezone','xgsystem','xgzonecode','fto','xocnoc','snowticketassignment',)
if user.is_authenticated:
edit = TemplateColumn(template_name='update.html')
delete = TemplateColumn(template_name='delete.html')
app urls.py
from django.urls import path, include
from .views import HomePageView, SearchResultsView, EsgCreateView, EsgUpdateView, EsgDeleteView, EsgDetailView
urlpatterns = [
path('search/', SearchResultsView.as_view(),name='search_results',),
path('', HomePageView.as_view(), name='home'),
path('createform/', EsgCreateView.as_view(), name='createform'),
path('update/<int:pk>', EsgUpdateView.as_view(), name='update'),
path('delete/<int:pk>', EsgDeleteView.as_view(), name='delete' ),
path('details/<int:pk>', EsgDetailView.as_view(), name='details'),
]
views.py
from .models import EsgDatabase
from django.urls import reverse_lazy
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import render
from django.views.generic import TemplateView, ListView, CreateView, UpdateView, DeleteView, DetailView
from django_tables2 import SingleTableView
from esgsheet.tables import EsgListViewTable
class EsgDetailView(DetailView):
template_name = 'details.html'
model = EsgDatabase
table_class = EsgListViewTable
context_object_name = 'esgdetail'
def get_success_url(self):
return reverse_lazy('details',kwargs={'pk':self.object.id})
class HomePageView(TemplateView):
template_name = 'home.html'
context_object_name = 'esghome'
#method_decorator(login_required, name='dispatch')
class EsgDeleteView(DeleteView):
template_name = 'delete.html'
model = EsgDatabase
table_class = EsgListViewTable
# success_url = reverse_lazy('home')
context_object_name = 'deleteview'
def get_success_url(self):
return reverse_lazy('home',kwargs={'pk':self.object.id})
#method_decorator(login_required, name='dispatch')
class EsgUpdateView(UpdateView):
model = EsgDatabase
fields = '__all__'
table_class = EsgListViewTable
template_name = 'update.html'
context_object_name = 'esgupdate'
strong textdef get_success_url(self):
return reverse_lazy('details', kwargs={'pk':self.object.id})
#method_decorator(login_required, name='dispatch')
class EsgCreateView(CreateView):
model = EsgDatabase
fields = '__all__'
template_name = 'forms.html'
def get_success_url(self):
return reverse_lazy('details', kwargs={'pk':self.object.id})
class SearchResultsView(SingleTableView):
model = EsgDatabase
table_class = EsgListViewTable
template_name = 'search_results.html'
SingleTableView.table_pagination = False
def get_queryset(self):
query = self.request.GET.get('q')
if query:
object_list = EsgDatabase.objects.filter(
Q(role__icontains=query) | Q(hq__icontains=query) |
Q(system__icontains=query) | Q(market__icontains=query) |Q(state__icontains=query) |
Q(zone__icontains=query) |Q(arrisseachangezone__icontains=query) |Q(xgsystem__icontains=query) |
Q(xgzonecode__icontains=query) | Q(syscode__icontains=query) |Q(fto__icontains=query) |
Q(xocnoc__icontains=query) |Q(snowticketassignment__icontains=query)
)
else:
object_list = self.model.objects.none()
return object_list
base.html
{% load django_tables2 %}
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<center>
{% block title %}
{% endblock title %}
</center>
</head>
<body>
<!-- {% url 'home' as home %}
{% if request.path != home %}
<center> <br>
<form action="{% url 'search_results' %}" method="GET">
<input name='q' type="text" placeholder="Search ESG Database">
</form> <br>
</center>
{% endif %} -->
{% block content %}
{% endblock content %}
</body>
</html>
home.html
{% extends 'base.html' %}
{% block title %}
<h1>ESG Database</h1>
{% endblock title %}
{% block content %}
<center>
<form action="{% url 'search_results' %}" method="GET">
<input name='q' type="text" placeholder="Search ESG Database">
</form>
</center>
{% endblock content %}
delete.html
{% block title %}
{% endblock title %}
{% block content %}
<form method="POST">{% csrf_token %}
</form>
{% if user.is_authenticated %}
<a type="submit" class="btn btn-danger btn-sm" href="{% url 'delete' record.id %}" >Delete.html</a>
{% endif %}
{% endblock content %}
update.html
{% extends 'base.html' %}
{% block title %}
{% endblock title %}
{% block content %}
<form method="POST">
{% csrf_token %}
{{form.as_p}}
{% if user.is_authenticated %}
<a type="submit" class="btn btn-info btn-sm" href="{% url 'update' record.id %}" >Update.html</a>
{% endif %}
</form>
{% endblock content %}
search_results.html
{% extends 'base.html' %}
{% load render_table from django_tables2 %}
{% block title %}
<h1>ESG Database Results</h1>
{% endblock title %}
{% block content %}
{% render_table table %}
{% endblock content %}
forms.html
{% extends 'base.html' %}
{% block title %}
<h1>Create ESG Entry</h1>
{% endblock title %}
{% block content %}
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
{% if user.is_authenticated %}
<input type="submit" value="Submit">
{% endif %}
</form>
{% endblock content %}
details.html
{% extends 'base.html' %}
{% block title %}
<h1>Updated Detail View</h1>
{% endblock title %}
{% block content %}
<table class="table table-hover">
<thead>
<th>Role</th>
<th>HQ</th>
<th>System</th>
<th>Market</th>
<th>State</th>
<th>Zone</th>
<th>Arris/SeaChange Zone</th>
<th>xG System</th>
<th>xG Zone Code</th>
<th>Syscode</th>
<th>FTO</th>
<th>XOC/NOC</th>
<th>SNOW Ticket Assignment</th>
</thead>
<tbody>
<tr>
<td>{{esgdetail.role}}</td>
<td>{{esgdetail.hq}} </td>
<td>{{esgdetail.system}} </td>
<td>{{esgdetail.market}} </td>
<td>{{esgdetail.state}} </td>
<td>{{esgdetail.zone}} </td>
<td>{{esgdetail.arrisseachangezone}} </td>
<td>{{esgdetail.xgsystem}} </td>
<td>{{esgdetail.xgzonecode}} </td>
<td> {{esgdetail.syscode}} </td>
<td> {{esgdetail.fto}} </td>
<td>{{esgdetail.xocnoc}} </td>
<td> {{esgdetail.snowticketassignment}} </td>
<!-- <td>
edit
delete
</td> -->
</tr>
</tbody>
</table>
{% endblock content %}
Thanks to #funkybob at #django irc room. First I had to delete comments from my code because it was being parsed throwing NoReverseMatch errors. Second, I had to remove context_object_name from update and delete views.

Is possible to write XSS vulnerable flask web app?

I'm trying to write a stored xss vulnerable flask web app. My app receive input via this input field <input type="text" name="content" id="content" /> and then show User input into an HTML table.
I tried to insert a script like <script>alert(1)</script> into the input field but when it is shown, the script isn't triggered.
Here is my code:
app.py
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return '<Task %r>' % self.id
#app.route('/', methods = ['POST', 'GET'])
def index():
if request.method == 'POST':
task_content = request.form['content']
new_task = Todo(content=task_content)
try:
db.session.add(new_task)
db.session.commit()
return redirect('/')
except:
return "There was an issue adding your task"
else:
tasks = Todo.query.order_by(Todo.date_created).all()
return render_template("index.html", tasks=tasks)
if __name__ == "__main__":
app.run(debug=True)
index.html
{% extends 'base.html' %}
{% block head %}
<title>Task Master</title>
{% endblock %}
{% block body %}
<div class="content">
<h1 style="text-align: center">Task Master</h1>
{% if tasks|length < 1 %}
<h4 style="text-align: center">There are no tasks. Create one below!</h4>
{% else %}
<table>
<tr>
<th>Task</th>
<th>Added</th>
<th>Actions</th>
</tr>
{% for task in tasks %}
<tr>
<td>{{ task.content }}</td>
<td>{{ task.date_created.date() }}</td>
<td>
Delete
<br />
Update
</td>
</tr>
{% endfor %}
</table>
{% endif %}
<div class="form">
<form action="/" method="POST">
<input type="text" name="content" id="content" />
<input type="submit" value="Add Task" />
</form>
</div>
</div>
{% endblock %}
base.html
<!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/main.css') }}"
>
{% block head %}{% endblock %}
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>
I follow this example.
This is a screen of the form:(https://i.stack.imgur.com/870tY.png)
and this is a screen of the HTML after the script submission:(https://i.stack.imgur.com/U1Jdd.png)
How do I make the script executable when the page is loaded?
Flask uses Jinja2 template engine and Flask enables automatic escaping on Jinja2 by default.
If you really want to allow XSS, change {{ task.content }} to {{ task.content|safe }} on your template.
More information: https://flask.palletsprojects.com/en/1.1.x/templating/#controlling-autoescaping

Flask RadioField is not working in form POST

Can someone please help resolving RadioField Post issue in below code snippet
As below code is not moving form.validate_on_submit()
**forms.py**
class validatingSPLForm(FlaskForm):
srcfile = FileField('Select Source ZIP', validators=[FileRequired(), FileAllowed(['zip'], 'Only ZIP files are allowed')])
submit = SubmitField("Validate")
proceed = IntegerField()
SPLFiles = RadioField('SPL', choices=[])
archiveresult = []
**routes.py**
app.route('/validatingSPLForm', methods=['GET', 'POST'])
def validatingSPLForm():
form = validatingSPLForm()
if request.method == 'POST':
if form.validate_on_submit():
form.SPLFiles.choices = [(elem.name, elem.des) for elem in form.archiveresult]
**validatingSPLForm.html**
{% extends "layout.html" %}
{% block content %}
<div class="content-section">
<form method="POST" action="" enctype="multipart/form-data">
</form>
</div>
{% endblock content %}
{% block content1 %}
<div class="content-section">
<h6><b class="text-success">"{{ form.srcfile.data.filename }}"</b> is valid, select one of the below SPL for further validation </h6>
{{ form.SPLFiles() }}
</div>
{% endblock content1 %}

Unable to Fetch particular product for each category

I am always getting all the food items in all Categories.
I want to display each Category with each food item.
Need to display Category with item belonging to that Category.
Please someone help me on this issue to resolve. I have tried looking over internet but couldn't find the solution to it
models.py
class Category(models.Model):
category_name = models.CharField(max_length=50)
def __str__(self):
return self.category_name
class Menu(models.Model):
dish_name = models.CharField(max_length=200, verbose_name='Name of Dish')
Desc = models.TextField(verbose_name='Dish Description')
Amount = models.IntegerField(null=False, blank=False, verbose_name='Amount of Dish')
date_posted = models.DateTimeField(default=timezone.now, verbose_name='Dish Date Posted')
category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1)
def __str__(self):
return self.dish_name
views.py
def menu(request):
products = Menu.objects.all()
categories = Category.objects.all()
data = {}
data['products'] = products
data['categories'] = categories
template = 'food/menu.html'
return render(request, template, data)
html
{% for category in categories %}
{% if categories %}
<div class="col-xs-12 col-sm-6">
<div class="menu-section">
<h2 class="menu-section-title">{{ category.category_name }}</h2>
<hr>
{% endif %}
{% for i in products %}
<div class="menu-item">
<div class="menu-item-name">{{ i.dish_name}}</div>
<div class="menu-item-price">Rs {{ i.Amount}}</div>
<div class="menu-item-description">{{ i.Desc}}</div>
</div>
{% endfor %}
</div>
</div>
{% endfor %}
you are not filtering products based on categoris.
I would suggest doing something like this with data:
data = {
'categories': {
category: Menu.objects.filter(category=category) for category in categories
}
}
and in html you can:
{% for category, products in categories.items %}
{% if products %}
<div class="col-xs-12 col-sm-6">
<div class="menu-section">
<h2 class="menu-section-title">{{ category.category_name }}</h2>
<hr>
{% for i in products %}
<div class="menu-item">
<div class="menu-item-name">{{ i.dish_name}}</div>
<div class="menu-item-price">Rs {{ i.Amount}}</div>
<div class="menu-item-description">{{ i.Desc}}</div>
</div>
{% endfor %}
</div>
</div>
{% endif %}
{% endfor %}

Edit and Update Method is Not working

My problem is, edit and update the values by using python-flask from client side. I don't have any idea about that and new python-flask using MySQL database. I tried this method for edit and update purpose.But, it's not working.Additionally the details will be added in database when we enter details and submit. anyone help me.
Here is vehicletype.html template.
{% extends "base.html" %}
{% block head %}
{{super()}}
{% endblock %}
{% block navbar %}
{{super()}}
{% endblock %}
{% block content %}
<div class="row">
<ol class="breadcrumb">
<li><a href="#">
<em class="fa fa-home"></em>
</a></li>
<li class="active">Vehicletype > Create Vehicletype</li>
</ol>
</div>
<div class="row">
<div class="col-md-6">
<form role="form" action="/post/vehicletype" method="post">
<div class="form-group">
<label>VehicleType: </label>
<input name="type" class="form-control" placeholder="enter vehicletype">
</div>
<input type="submit" class="btn btn-primary" value="Submit ">
<input type="reset" class="btn btn-default" value="Reset">
</form>
</div>
</div>
{% endblock %}
Here is the details.html
{% extends "base.html" %}
{% block head %}
{{super()}}
{% endblock %}
{% block navbar %}
{{super()}}
{% endblock %}
{% block content %}
<div class="row">
<ol class="breadcrumb">
<li><a href="#">
<em class="fa fa-home"></em>
</a></li>
<li class="active">Vehicletype>View</li>
</ol>
</div><!--/.row-->
<div class="row">
<div class="col-md-12">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>
Id
</th>
<th>
VehicleType
</th>
<th>
Dateofsub
</th>
<!--<th>
Control
</th>-->
<th>
Delete
</th>
</tr>
</thead>
{% for values in vehicletype %}
<tr>
<th>{{values.id}}</th>
<td>{{values.type}}</td>
<td>{{values.dateofsub}}</td>
<!--<td>Reset Password</td>-->
<td>Delete</td>
<td>edit</td>
</tr>
{% endfor %}
</table>
<em class="fa fa-xl fa-plus-circle color-blue" ></em>
</div>
</div>
{% endblock %}
python code for Edit method:
class VehicetypeForm(FlaskForm):
type=StringField('Type')
#app.route('/control/edit/<int:id>',methods=['POST','GET','PATCH'])
def edit(id):
form = VehicetypeForm(request.form)
mysql = pymysql.connect("0.0.0.0", "tnxt", "tnxt", "transport")
cur = mysql .cursor()
cur.execute('SELECT * FROM vehicletype WHERE id= %s',[id])
type=cur.fetchall()
# form.type.data=type
if request.method=='PATCH' and form.validate():
#type=form.type.data
mysql = pymysql.connect("0.0.0.0", "tnxt", "tnxt", "transport")
cur=pymysql .cursor()
cur.execute('UPDATE vehicletype SET type=%s WHERE id=%s',(type,id))
mysql.connection.commit()
cur.close()
flash('success')
return redirect(url_for('vehicle_type'))
return render_template('vehicletype.html',form=form)
In this python code update method is not working. But, when we give the details that details will be added in database. How to edit and update the values from client side.
Below is the good practice to create form using wtforms
class UserForm(Form):
name = StringField('Name')
father_name = StringField('Father Name')
# .... add fields you want
for field types - refer to this link
#app.route('/newuser', methods=['GET', 'POST'])
def add_user():
form = UserForm()
if form.validate_on_submit():
user_details = {
name: form.name.data,
fathername: form.father_name.data,
# add more fields
}
sqlsession.add(user_details)
return redirect(url_for('page_newuser'))
return render_template('newuser.html', form=form)
Once you have form then you can easily edit your content and directly save it to database
#app.route('/control/edituser/<int:id>',method=['post','get'])
def edit(id):
qry=sqlsession.query(Enduser).filter(Enduser.id==id).first()
form = UserForm(request.form, **qry)
if form.validate_on_submit():
form.populate_obj(qry)
sqlsession.update(qry)
sqlsession.commit()
return redirect(url_for('page_newuser'))
return render_template('newuser.html', form=form)

Resources