new to coding. I'm creating an inventory table'with the django framework. I'd like to be able to click on a table row (which is a part) that will then parse that row/part information to a detail view. from what I understand table rows are inline elements and inline elements are psuedo code which current HTML does not allow for an anchor tag to be thrown in (bad practice?) so I need to use some javascript. Currently, the inventory view shows when I use runserver (http://127.0.0.1:8000/inventory/) but clicking on any row does nothing. Here is what I have so far;
inventory.html
{% extends "base.html" %}
{% block body %}
<br>
<table class="table table-hover">
<thead>
<tr>
<th>Part Number</th>
<th>Description</th>
<th>Location</th>
<th>Supplier</th>
<th>S.O.H</th>
</tr>
</thead>
<tbody>
{% for part in parts %}
<!-- need to make these table rows link to their respective parts
class="table_row" href="{{ selected_part.partnumber }}/detail">{{ selected_part.partnumber }}-->
<tr data-href="{% url 'detail' part.pk %}">
<td>{{ part.pk }}</td>
<td>{{ part.partnumber }}</td>
<td>{{ part.description }}</td>
<td>{{ part.location }}</td>
<td>{{ part.supplier }}</td>
<td>{{ part.stockonhand }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('inventory/', inventory_list, name='inventory'), # URL path for inventory_list view
path('<str:pk>/', part_information, name='detail'),
path('', index, name='index'),
]
custom.js
$('tr[data-href]').on("click", function() {
document.location = $(this).data('href');
});
base.html has <script src="/docs/4.4/dist/js/custom.js"></script> before the </body> tag.
I think the issues is in my javascript file. I'm pretty new to this and simplified explanations would be greatly appreciated
Use the below in your custom.js file. When the page is loaded then this function $(document).ready() gets executed initialising the tr on what to do 'On Click'
$(document).ready(function(){
$('table tr').click(function(){
window.location = $(this).data('href');
return false;
});
});
Related
I have a list of entries. Insider the list of entries I have a link to individual entries. I have an update form that updates one field.
I want to open the update form inside a new window. The user then submits the form is directed to a success page which currently has a timed close.
The issue I am encountering is with the inline JavaScript which opens the form in a new window. When I attempt to assign the kwarg on the URL it the JavaScript does not change with each entry in the list.
I have limited JavaScript, and jQuery knowledge.
I just want the JavaScript to open a new window for each update form.
I have included the template below.
<thead>
<tr>
<th>Script No.</th>
<th>Entered on</th>
<th>Patient</th>
<th>Email</th>
<th>Product</th>
<th>Form</th>
<th>Units</th>
<th>Dispensing Price</th>
<th>Status</th>
<th>Dispatch Date</th>
<th>Entered by</th>
<th></th>
</tr>
</thead>
<tbody>
{% for script in scripts %}
<tr>
<td>{{script.pk}}</td>
<td>{{script.entered_on}}</td>
<td>{{script.patient}}</td>
<td>{{script.patient.email}}</td>
<td>{{script.product}}</td>
<td>{{script.product.form.description}}</td>
<td>{{script.quantity}}</td>
<td>$ {{ script.dispensing_price }}</td>
{% if script.dispatch_date is not none %}
<td>{{script.get_script_status_display}}</td>
{% else %}
<td>{{script.get_script_status_display}}</td>
{% endif %}
<td><a href ="#" onclick="updateStatus()" style="float:right;">
<script>var url = "{% url "script:script_update_status" script.pk %}";
function updateStatus() {var myWindow = window.open(url, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=250");}
</script></td>
{% if script.dispatch_date is none %}
<td>Not Sent</td>
{% else %}
<td>{{script.dispatch_date}}</td>
{% endif %}
<td>{{script.created_by.first_name}} {{script.created_by.last_name}}</td>
<td><small>View | Edit | Lab Label | <a href="{% url 'label:dispense_label' script.pk %}">Dispense Label
</a> | Shipping Label | Repeat</small></td>
</tr>
{% endfor %}
</tbody>
</table> ```
Kind Regards
AC
By default bootstrap table is sorted using the first column. This setting can be changed with data-sort-name="column_name" data-sort-order="asc/desc" as mentioned here link.
In my scenario the column names are created dynamically based on a python script. As such the data-sort-name option is not helpful.
Is it possible to specify the column I want the default sorting to be done by the column index?
<table id="table_example"
class="table table-striped"
data-toggle="table"
<thead>
<tr>
{% for col in column_names %}
<th>{{col}}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in row_data %}
<tr>
{% for col, row_ in zip(column_names, row) %}
<td>{{row_}}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
I've solved the problem by adding the following script with column index 1:
<script>
$(document).ready(function () {
$('#table_example').DataTable({
"order": [[ 1, "desc" ]]
});
});
</script>
I'm using a datatable in Bootstrap to create a table which jinja2 will populate with values passed from Flask, example below:
Name
URL
google
www.google.com
reddit
www.reddit.com
{% for site in results %}
<tr>
<td>{{ site['sitename'] }}</td>
<td>{{ site['url'] }}</td>
</tr>
{% endfor %}
I also have site['new_url'] which is passed in results. I want to make the site['url'] clickable and have that toggle between site['url'] and site['new_url'] when clicked.
I'd like to implement using JS if possible or if there is another easier way I'm up for that too!
Any help is appreciated!
A Js solution:
{% for site in results %}
<tr>
<td>{{ site['sitename'] }}</td>
<td onclick="swapText()" id="target">{{ site['url'] }}</td>
</tr>
<script>
function swapText() {
var x = document.getElementById("target");
if (x.innerHTML === "{{ site['url'] }}") {
x.innerHTML = "{{ site['new_url'] }}";
} else {
x.innerHTML = "{{ site['url'] }}";
}
}
</script>
{% endfor %}
I've got a large template file here that I'm accessing in a for loop to print a table with some values in it. When a user clicks on one of those values I'd like it to carry over just that 1 json block to another page in order to have it prefill some fields. I'm having trouble getting my program to select that single entry in the json dict in order to render the next page. Here's the code involved:
views.py
#apps.route('/add')
#login_required
#admin_required
def view_apps():
""" View available apps """
template = Template.query.all()
dir_path = os.path.dirname(os.path.realpath(__file__))
json_content = combine_json_templates()
print(json_content)
print(len(json_content))
return render_template('apps/add_app.html', apps=json_content)
def combine_json_templates():
master_list = []
cwd = os.getcwd()
print(cwd)
json_storage = 'app/storage/templates/json/'
for file in os.listdir(json_storage):
with open(json_storage + file) as json_path:
json_content = json.load(json_path)
for item in json_content:
master_list.append(item)
return master_list
#apps.route('/add/<int:app_id>')
#apps.route('/add/<int:app_id>/info')
def app_info(app_id):
app = json_content[""+app_id+""]
print(app)
add_app.html (code that displays the table and contains the onclick:
<div style="overflow-x: scroll;">
<table class="ui searchable sortable unstackable selectable celled table">
<thead>
<tr onclick="window.location.href = '{{ url_for('apps.app_info', app_id=apps.pop(['name'])) }}';">
<th class="sorted ascending">Title</th>
<th>Desctiption</th>
<th>Catagory</th>
<th>Platform</th>
</tr>
</thead>
<tbody>
{% for a in apps | sort(attribute='title') %}
<tr>
<td>{{ a.title }}</td>
<td>{{ a.description }}</td>
<td>{{ a.categories }}</td>
<td>{{ a.platform }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
The part that I'm having trouble with is getting a unique value in order to pass it onto the next page and reference the correct json.
<tr onclick="window.location.href = '{{ url_for('apps.app_info', app_id=apps.pop(['name'])) }}';">
Should I be using a different method for referencing the json file? Should I be modifying it when loading the json files in order to add some kind of key?
This is my first flask project so I'm not sure the best way to go about this.
I think I have an approach, the question is whether you like it.
# ./__init__.py
def create_app():
app = Flask(__name__,
# default: ./var/app-instance/
instance_relative_config=True,
)
app.config.from_mapping(
SECRET_KEY=b'change-me\n',
)
try:
os.makedirs(app.instance_path)
except OSError:
pass
# init endpoints/blueprints here
from .apps import create_module as apps_create_module
apps_create_module(app)
return app
# ./app/apps/view.py
# TODO: move this to the apps configuration file
JSON_TEMPLATES_DIR = 'storage/templates/json'
def load_json_data(path):
data = []
for fname in glob(os.path.join(path, '*.json')):
with open(fname) as fp:
dataset = json.load(fp)
data.extend(dataset)
return data
#apps.route('/add')
#login_required
#admin_required
def list_apps():
'''View available apps'''
apps = load_json_data(
os.path.join(current_app.instance_path,
JSON_TEMPLATES_DIR))
return render_template('apps/add_app.html', **locals())
#apps.route('/add/info', methods=['POST'])
#csrf.exempt
def app_info():
'''View selected app'''
ident = request.form.get('ident', None)
if ident:
try:
app = json.loads(ident)
print(app)
except: pass
return render_template('apps/app_info.html', **locals())
<!-- "./app/templates/apps/add_app.html" -->
<div style="overflow-x: scroll;">
<table class="ui searchable sortable unstackable selectable celled table">
<thead>
<tr>
<th class="sorted ascending">Title</th>
<th>Description</th>
<th>Catagory</th>
<th>Platform</th>
</tr>
</thead>
<tbody>
{% for a in apps | sort(attribute='title') %}
<tr id="app-entry-{{loop.index}}">
<td>
<div class="namecell">
<span class="nametext" style="display: block;">{{ a.title }}</span>
<span class="btn-group" role="group" style="margin-top: 1rem">
<form method="post" action="{{url_for('apps.app_info')}}">
<input type="hidden" name="ident" value='{{app | tojson | safe}}' />
<button type="submit">Setup</button>
</form>
</span>
</div>
</td>
<td>{{ a.description }}</td>
<td>{{ a.categories }}</td>
<td>{{ a.platform }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
I'm making a website using flask.
It displays a list using sql in top.html in which each element is a hypertext.
<table class="table table-striped">
<thead></thead>
<tr>
<th>Company</th>
</tr></thead>
<tbody>
{% for company in companies %}
<tr>
<td>{{ company.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
So i want to know which hypertext is clicked from the list so that i could load its respective content in /text.
please provide the python code also(flask code).
First put company unique identifier to each <a for example <a data-id="11" ...
Then add event listeners on each <a like this...
var companyLinks = document.querySelectorAll('.table-striped a');
for (var i = 0; i < companyLinks.length; i += 1) {
companyLinks[i].addEventListener('click', function (e) {
// get the company id of clicked link
var companyId = e.target.dataset.id;
// now do what you like with the company id
// for example you can send an AJAX call to your backend
});
}