Link to specific tab Bootstrap - javascript

I'm developing a site with Django Framework and I'm trying to create a way for when a user access a link like http://www.example.com/site/#users_rating it opens a specific tab in the page.
I tried the following code that I found on the Internet (I'm new in JavaScript/JQuery), it isn't working:
<script type="text/javascript">
$(function() {
// Javascript to enable link to tab
var url = document.location.toString();
if (url.match('#')) {
$('.nav-tabs a[href=#'+url.split('#')[1]+']').tab('show') ;
}
// Change hash for page-reload
$('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
window.location.hash = e.target.hash;
});
});
</script>
My template uses BootStrap 3, here is the HTML code (with some Django tags):
<div class="col-md-12" style="margin: 0 auto;">
<section class="panel">
<header class="panel-heading tab-bg-dark-navy-blue">
<ul class="nav nav-tabs nav-justified ">
<li class="active">
<a data-toggle="tab" href="#overview">
{% trans "Overview" %}
</a>
</li>
<li class="">
<a data-toggle="tab" href="#timeline">
{% trans "Timeline" %}
</a>
</li>
<li class="">
<a data-toggle="tab" href="#users_rating">
{% trans "Users Ratings" %} ({{ ptc.userrating.count }})
</a>
</li>
<li class="">
<a data-toggle="tab" href="#rating">
{% trans "Our Rating" %}
</a>
</li>
</ul>
</header>
<div class="panel-body">
<div class="tab-content tasi-tab">
<!-- Overview Tab-Pane -->
<div id="overview" class="tab-pane active">
{% include 'overview.html' %}
</div>
<!-- Timeline Tab-Pane -->
<div id="timeline" class="tab-pane">
{% include 'timeline.html' %}
</div>
<!-- User Rating Tab-Pane -->
<div id="users_rating" class="tab-pane">
{% include 'users_rating.html' %}
</div>
<!-- Our Rating Tab-Pane -->
<div id="rating" class="tab-pane">
{% include 'rating.html' %}
</div>
</div>
</div>
</section>
</div>
How can I open an specific tab according to an URL in my site?

Following code works for me
HTML
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery.min.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div class="col-md-12" style="margin: 0 auto;">
<section class="panel">
<header class="panel-heading tab-bg-dark-navy-blue">
<ul class="nav nav-tabs nav-justified ">
<li class="active">
<a data-toggle="tab" href="#overview">
{% trans "Overview" %}
</a>
</li>
<li class="">
<a data-toggle="tab" href="#timeline">
{% trans "Timeline" %}
</a>
</li>
<li class="">
<a data-toggle="tab" href="#users_rating">
{% trans "Users Ratings" %} ({{ ptc.userrating.count }})
</a>
</li>
<li class="">
<a data-toggle="tab" href="#rating">
{% trans "Our Rating" %}
</a>
</li>
</ul>
</header>
<div class="panel-body">
<div class="tab-content tasi-tab">
<!-- Overview Tab-Pane -->
<div id="overview" class="tab-pane active">
{% include 'overview.html' %}
</div>
<!-- Timeline Tab-Pane -->
<div id="timeline" class="tab-pane">
{% include 'timeline.html' %}
</div>
<!-- User Rating Tab-Pane -->
<div id="users_rating" class="tab-pane">
{% include 'users_rating.html' %}
</div>
<!-- Our Rating Tab-Pane -->
<div id="rating" class="tab-pane">
{% include 'rating.html' %}
</div>
</div>
</div>
</section>
</div>
</body>
</html>
JS
<script type="text/javascript">
$(function() {
// Javascript to enable link to tab
var hash = document.location.hash;
if (hash) {
console.log(hash);
$('.nav-tabs a[href='+hash+']').tab('show');
}
// Change hash for page-reload
$('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
window.location.hash = e.target.hash;
});
});
</script>

Thanks a bunch. With newer versions of JQuery (mine=3.3.1) you need to make a little alteration:
<script>
$(function() {
// Javascript to enable link to tab
var hash = document.location.hash;
if (hash) {
console.log(hash);
$('.nav-tabs a[href=\\'+hash+']').tab('show');
}
// Change hash for page-reload
$('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
window.location.hash = e.target.hash;
});
});
</script>
Hope this saves someone the hour I lost

Related

NoReverseMatch at /cart/ Reverse for 'ProductView' not found. 'ProductView' is not a valid view function or pattern name

Error
NoReverseMatch at /cart/
Reverse for 'ProductView' not found. 'ProductView' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://127.0.0.1:8000/cart/
Django Version: 3.2.3
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'ProductView' not found. 'ProductView' is not a valid view function or pattern name.
Error Screenshot
This is where it shows me error, when I try to add a product to cart sessions,tho the product it added to cart sessions but when the url for cart-details is called, while loading the main base.html file it gives me a error that productView cannot be found
ProductApp Templates 'app/base.html'
<!doctype html>
{% load static %}
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<base href="/">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins:200,300,400,500,600,700,800&display=swap" type="text/css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lora:400,400i,700,700i&display=swap" type="text/css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Amatic+SC:400,700&display=swap" type="text/css">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<!-- <link rel="stylesheet" href="{% static 'app/css/open-iconic-bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'app/css/animate.css' %}"> -->
<!--Owl Carousel CSS-->
<link rel="stylesheet" href="{% static 'app/css/owl.theme.default.min.css' %}" type="text/css">
<link rel="stylesheet" href="{% static 'app/css/magnific-popup.css' %}" type="text/css">
<link rel="stylesheet" href="{% static 'app/css/aos.css' %}" type="text/css">
<link rel="stylesheet" href="{% static 'app/css/ionicons.min.css' %}" type="text/css">
<link rel="stylesheet" href="{% static 'app/css/bootstrap-datepicker.css' %}" type="text/css">
<link rel="stylesheet" href="{% static 'app/css/jquery.timepicker.css' %}" type="text/css">
<link rel="stylesheet" href="{% static 'app/css/flaticon.css' %}" type="text/css">
<link rel="stylesheet" href="{% static 'app/css/icomoon.css' %}" type="text/css">
<link rel="stylesheet" href="{% static 'app/css/owl.carousel.min.css' %}" type="text/css">
<!--FontAwesome CSS-->
<link rel="stylesheet" href="{% static 'app/css/all.min.css' %}" type="text/css">
<!--Custom CSS-->
<link rel="stylesheet" href="{% static 'app/css/style.css' %}" type="text/css">
<!-- <link rel="stylesheet" href="{% static 'app/css/style.css' %}"> -->
<title>VEGEFOODS | {% block title %} {% endblock title %} </title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark ftco_navbar bg-dark ftco-navbar-light" id="ftco-navbar">
<div class="container">
<a class="navbar-brand" href="{% url 'app:home' %}">VEGEFOODS</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
</ul>
<div>
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="{% url 'app:home' %}">Home</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="electronicsDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Shop
</a>
<ul class="dropdown-menu" aria-labelledby="electronicsDropdown">
<li><a class="dropdown-item" href="{% url 'app:Vegetables' %}">Vegatables</a></li>
<li><a class="dropdown-item" href="{% url 'app:Fruits' %}">Fruits</a></li>
<li><a class="dropdown-item" href="{% url 'app:Dried' %}">Dried</a></li>
</ul>
</li>
<li class="nav-item mx-2">
<span class="badge bg-danger">4</span> Cart
</li>
{% if request.user.is_authenticated %}
<li class="nav-item dropdown mx-2">
<a class="nav-link dropdown-toggle" href="#" id="profileDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
{{request.user.username.title}}
</a>
<ul class="dropdown-menu" aria-labelledby="profileDropdown">
<li><a class="dropdown-item" href="{% url 'app:profile' %}">Profile</a></li>
<li><a class="dropdown-item" href="{% url 'app:orders' %}">Orders</a></li>
<li><a class="dropdown-item" href="{% url 'app:passwordchange' %}">Change Password</a></li>
<li><a class="dropdown-item" href="{% url 'app:logout' %}">Logout</a></li>
</ul>
</li>
{% else %}
<li class="nav-item mx-2">
Login
</li>
{% endif %}
</ul>
</div>
</div>
</div>
</nav>
{% block banner_slider %} {% endblock banner_slider %}
{% block main-content %} {% endblock main-content %}
<!-- Start Footer -->
<footer class="ftco-footer ftco-section">
<div class="container">
<div class="row">
<div class="mouse align-items-center">
<a href="#" class="mouse-icon align-items-center">
<div class="mouse-wheel align-items-center"><span class="ion-ios-arrow-up align-items-center"></span></div>
</a>
</div>
</div>
<div class="row mb-5">
<div class="col-md">
<div class="ftco-footer-widget mb-4">
<h2 class="ftco-heading-2">Vegefoods</h2>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p>
<ul class="ftco-footer-social list-unstyled float-md-left float-lft mt-5">
<li class="ftco-animate"><span class="icon-twitter"></span></li>
<li class="ftco-animate"><span class="icon-facebook"></span></li>
<li class="ftco-animate"><span class="icon-instagram"></span></li>
</ul>
</div>
</div>
<div class="col-md">
<div class="ftco-footer-widget mb-4 ml-md-5">
<h2 class="ftco-heading-2">Menu</h2>
<ul class="list-unstyled">
<li>Shop</li>
<li>About</li>
<li>Journal</li>
<li>Contact Us</li>
</ul>
</div>
</div>
<div class="col-md-4">
<div class="ftco-footer-widget mb-4">
<h2 class="ftco-heading-2">Help</h2>
<div class="d-flex">
<ul class="list-unstyled mr-l-5 pr-l-3 mr-4">
<li>Shipping Information</li>
<li>Returns & Exchange</li>
<li>Terms & Conditions</li>
<li>Privacy Policy</li>
</ul>
<ul class="list-unstyled">
<li>FAQs</li>
<li>Contact</li>
</ul>
</div>
</div>
</div>
<div class="col-md">
<div class="ftco-footer-widget mb-4">
<h2 class="ftco-heading-2">Have a Questions?</h2>
<div class="block-23 mb-3">
<ul>
<li><span class="icon icon-map-marker"></span><span class="text">203 Fake St. Mountain View, San Francisco, California, USA</span></li>
<li><span class="icon icon-phone"></span><span class="text">+2 392 3929 210</span></li>
<li><span class="icon icon-envelope"></span><span class="text">info#yourdomain.com</span></li>
</ul>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-center">
<p>
Copyright # 2021
</p>
</div>
</div>
</div>
</footer> <!-- End Footer -->
<!-- loader -->
<!-- <div id="ftco-loader" class="show fullscreen"><svg class="circular" width="48px" height="48px"><circle class="path-bg" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke="#eeeeee"/><circle class="path" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke-miterlimit="10" stroke="#F96D00"/></svg></div> -->
<!-- Jquery -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<!-- Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
<script src="{% static 'app/js/owl.carousel.min.js' %}"></script>
<script src="{% static 'app/js/all.min.js' %}"></script>
<script src="{% static 'app/js/myscript.js' %}"></script>
<script src="{% static 'app/js/main.js' %}"></script>
<script src="{% static 'app/js/jquery.min.js' %}"></script>
<script src="{% static 'app/js/jquery-migrate-3.0.1.min.js' %}"></script>
<script src="{% static 'app/js/popper.min.js' %}"></script>
<script src="{% static 'app/js/bootstrap.min.js' %}"></script>
<script src="{% static 'app/js/jquery.easing.1.3.js' %}"></script>
<script src="{% static 'app/js/jquery.waypoints.min.js' %}"></script>
<script src="{% static 'app/js/jquery.stellar.min.js' %}"></script>
<script src="{% static 'app/js/owl.carousel.min.js' %}"></script>
<script src="{% static 'app/js/jquery.magnific-popup.min.js' %}"></script>
<script src="{% static 'app/js/jquery.animateNumber.min.js' %}"></script>
<script src="{% static 'app/js/bootstrap-datepicker.js' %}"></script>
<script src="{% static 'app/js/scrollax.min.js' %}"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false"></script>
<script src="{% static 'app/js/google-map.js' %}"></script>
<!-- <script src="https://unpkg.com/aos#next/dist/aos.js"></script> -->
<script src="{% static 'app/js/aos.js' %}"></script>
</body>
</html>
ProductApp view.py
def ProductView(request):
vegetables = Products.objects.filter(Sub_Category_ID__CategoryID__name='Vegetables')
return render(request, 'app/home.html',{'Vegetables':vegetables})
ProductApp urls.py
from re import template
from django.urls import path
from app import views
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from.forms import LoginForm, MyPasswordChangeForm
app_name='app'
urlpatterns = [
# path('', views.home),
path('',views.ProductView,name='home'),
path('product-detail/<int:pk>', views.ProductDetailView.as_view(), name='product-detail'),
# path('add-to-cart/', views.add_to_cart, name='add-to-cart'),
path('showcart/',views.show_cart,name='showcart'),
# path('pluscart/',views.plus_cart),
# path('minuscart/',views.minus_cart),
# path('removecart/',views.remove_cart),
# path('add-to-cart/<slug:data>', views.add_to_cart, name='add-to-cart_DATA'),
path('buy/', views.buy_now, name='buy-now'),
path('profile/', views.ProfileView.as_view(), name='profile'),
path('address/', views.address, name='address'),
path('orders/', views.orders, name='orders'),
# path('changepassword/', views.change_password, name='changepassword'),
path('Fruits/', views.Fruits, name='Fruits'),
path('Fruits/<slug:data>', views.Fruits, name='FruitsData'),
path('Dried/', views.Dried, name='Dried'),
path('Dried/<slug:data>', views.Dried, name='DriedData'),
path('Vegetables/', views.Vegetables, name='Vegetables'),
path('Vegetables/<slug:data>', views.Vegetables, name='VegetablesData'),
path('accounts/login/',auth_views.LoginView.as_view(template_name='app/login.html',authentication_form=LoginForm),name='login'),
path('passwordchange/',auth_views.PasswordChangeView.as_view(template_name='app/passwordchange.html',form_class=MyPasswordChangeForm, success_url='/passwordchangedone/'),name='passwordchange'),
path('passwordchangedone/',auth_views.PasswordChangeDoneView.as_view(template_name='app/passwordchangedone.html'),name='passwordchangedone'),
path('logout/',auth_views.LogoutView.as_view(next_page='login'),name='logout'),
# path('login/', views.login, name='login'),
path('registration/', views.CustomerRegistrationView.as_view(), name='customerregistration'),
path('checkout/', views.checkout, name='checkout'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
CartApp Views.py
from cart.forms import CartAddProductForm
from django.shortcuts import get_object_or_404, redirect, render
from app.models import Products
from django.views.decorators.http import require_POST
from .cart import Cart
from .forms import CartAddProductForm
# Create your views here.
#require_POST
def cart_add(request, product_id):
cart = Cart(request)
product = get_object_or_404(Products, id=product_id)
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product, quantity=cd['quantity'])
return redirect('cart:cart_detail')
def cart_remove(request,product_id):
cart = Cart(request)
product = get_object_or_404(Products, id=product_id)
cart.remove(product)
return redirect('cart:car_detail')
def cart_detail(request):
cart = Cart(request)
return render (request ,'cart/cartdetail.html',{'cart':cart})
CartApp urls
from django import urls
from django.urls import path
from django.urls.conf import include
from . import views
app_name='cart'
extra_patterns = [
path('add/carts/<int:product_id>/', views.cart_add, name='cart_add'),
]
urlpatterns=[
path ('add/',include(extra_patterns)),
path ('remove/<int:product_id>/',views.cart_remove,name='cart_remove'),
path ('',views.cart_detail,name='cart_detail'),
]
** CartApp Template 'detail.html'**
{% extends 'app/base.html' %}
{% load static %}
{% block title %}Cart{% endblock title %}
{% block main-content %}
<div class="container my-5">
<div class="row">
<h1 class="text-center mb-5">Shopping Cart</h1>
<div class="col-sm-8">
<div class="card">
<div class="card-body">
<h3>Cart</h3>
{% for items in cart %}
{% with product=items.product %}
<div class="row">
<div class="col-sm-3 text-center align-self-center">
<img src={{product.product_image.url}} alt="" srcset="" class="img-fluid img-thumbnail shadow-sm" height="150" width="150">
</div>
<div class="col-sm-9">
<div>
<h5>{{product.name}}</h5>
<p class="mb-2 text-muted small">Description: {{product.description}}</p>
<div class="my-3">
<label for="quantity">cart:</label>
<!-- <a class="minus-cart btn" pid="{{cart.productID.id}}"><i class="fas fa-minus-square fa-lg"></i></a> -->
<a class="minus-cart btn"><i class="fas fa-minus-square fa-lg"></i></a>
<span id="quantity">{{item.quantity}}</span>
<a class="plus-cart btn"><i class="fas fa-plus-square fa-lg"></i></a>
<!-- <a class="plus-cart btn" pid="{{cart.productID.id}}"><i class="fas fa-plus-square fa-lg"></i></a> -->
</div>
<div class="d-flex justify-content-between">
<form action="{% url 'cart:cart_remove' product.id %}" method="post">
<input type="submit" value="Remove">
{% csrf_token %}
</form>
<!-- <a class="btn btn-sm btn-secondary mr-3 remove-cart" pid="{{cart.productID.id}}"><strong>Remove Item</strong> </a> -->
<p class="mb-0"><span><strong>Rs. {{item.total_price}} </strong></span></p>
</div>
</div>
</div>
</div>
{% endwith %}
{% endfor %}
</div>
</div>
</div>
<div class="col-sm-4">
<div class="card">
<div class="card-body">
<h3>Total Amount</h3>
<ul class="list-group">
<!-- <li class="list-group-item d-flex justify-content-between align-items-center border-0 px-0 pb-0">Amount<span>Rs. <span id="amount">{{amount}}</span></span></li>
<li class="list-group-item d-flex justify-content-between align-items-center px-0">Shipping<span>Rs. 70.00</span></li> -->
<li class="list-group-item d-flex justify-content-between align-items-center border-0 px-0 mb-3">
<div>
<strong>Total</strong>
</div>
<span><strong>Rs. {{carts.get_total_price}}</strong></span>
</li>
</ul>
<!-- <div class="d-grid">Continue Shopping</div> -->
<!-- <div class="d-grid">Place Order</div> -->
</div>
</div>
</div>
</div>
</div>
{% endblock main-content %}
MainProject Urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path ('cart/', include('cart.urls',namespace='cart')),
path('',include('app.urls',namespace='app')),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
The issue is with this commented line,
<!-- <div class="d-grid">Continue Shopping</div> -->
Change it to
<!-- <div class="d-grid">Continue Shopping</div> -->
Even if the line is commented the Django template will render the URL template tags.

Get data from clicked elements Django

I have a page where User can select people to add in his team.
One side of the page is the list of the people to select.
When user click Add to the team, it goes to the right side where we have the list of the selected people.
I don't understand how I can get the data on the selected side from the view in django..
For example on the left:
<div class="card-body" id="team-list">
<p class="card-text">Select today's teammates:</p>
<ul class="list-group list-group-flush">
{% for tech in techs %}
<li class="list-group-item">
<span class="name" name="{{tech.id}}">{{tech.name}}</span>
<span class="move" style="float: right;">Add to the team</span>
</li>
{% endfor %}
and on the right:
<div class="card-body" id="selected-list">
<h3 class="title">You have selected the following teammates for today: </h3>
<ul class="list-group list-group-flush" style="list-style-type: none;">
</ul>
</div>
The click is handled by a little js click event like this:
var selected = document.querySelector('#selected-list ul');
var team = document.querySelector('#team-list ul');
function clickHandlerTeam(e){
if(e.target.classList.contains('move')){
if (e.target.textContent == 'Add to the team'){
console.log('changing add');
e.target.textContent ='Remove from the team';
selected.appendChild(e.target.parentNode);
} else {
console.log('changing remove');
e.target.textContent = 'Add to the team';
team.appendChild(e.target.parentNode);
}
console.log('****************');
}
return;
}
Thanks for your help
{{ selected_techs=[] }}
<div class="card-body" id="team-list">
<p class="card-text">Select today's teammates:</p>
<ul class="list-group list-group-flush">
{% for tech in techs %}
<li class="list-group-item">
<span class="name" name="{{tech.id}}">{{tech.name}}</span>
<span class="move" onclick="{{ selected_techs.append(tech) }}" style="float: right;">Add to the team</span>
</li>
{% endfor %}
</ul>
</p>
</div>
<div class="card-body" id="selected-list">
<h3 class="title">You have selected the following teammates for today: </h3>
<ul class="list-group list-group-flush" style="list-style-type: none;">
{% for tech in selected_techs %}
<li class="list-group-item">
<span class="name" name="{{tech.id}}">{{tech.name}}</span>
</li>
{% endfor %}
</ul>
</div>
I think this should solve your problem.
Just remember to add
Edit 1:
Try this
{% with selected_techs=[] %}
<div class="card-body" id="team-list">
<p class="card-text">Select today's teammates:</p>
<ul class="list-group list-group-flush">
{% for tech in techs %}
<li class="list-group-item">
<span class="name" name="{{tech.id}}">{{tech.name}}</span>
<span class="move" onclick="{% selected_techs.append(tech) %}" style="float: right;">Add to the team</span>
</li>
{% endfor %}
</ul>
</p>
</div>
<div class="card-body" id="selected-list">
<h3 class="title">You have selected the following teammates for today: </h3>
<ul class="list-group list-group-flush" style="list-style-type: none;">
{% for tech in selected_techs %}
<li class="list-group-item">
<span class="name" name="{{tech.id}}">{{tech.name}}</span>
</li>
{% endfor %}
</ul>
</div>
{% endwith %}
I found out my solution. I added a form tag for each of my elements in my template, and removed the ul, replaced it by a hidden input with a value of tech.id, and replaced the spans tags where the user used to click by buttons. Then handled it with the views.py by getting the ids.

Displaying jquery result, data there but not displaying

Using flask and jquery. I can see the data returned in dev tools but i'ts not displaying.
index.html
<!DOCTYPE HTML>
<html>
<head>
<title>integrator</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<!--[if lte IE 8]><script src="js/html5shiv.js"></script><![endif]-->
<script src="{{ url_for('static', filename='js/jquery.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/skel.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/skel-layers.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/init.js') }}"></script>
<script src="{{ url_for('static', filename='js/searchUpdate.js') }}"></script>
<link rel="stylesheet" href="{{ url_for('static', filename='css/skel.css') }}" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}" />
</head>
<body id="top">
<!-- Header -->
<header id="header" class="skel-layers-fixed">
<h1>Integrator</h1>
<nav id="nav">
<ul>
<li>Home</li>
<li>Acct. Info</li>
<li>Ticket Search</li>
<li>Sharepoint</li>
</ul>
</nav>
</header>
<!-- Banner -->
<section id="banner">
<div class="inner">
<h2>integrator</h2>
<p>CNG service integrator</p>
<p><form class="pure-form" action="/clientLookup" method="post">
<input type="text" class="pure-input-rounded" name="clientID">
<button type="submit" class="pure-button">Search</button>
</form></p>
</div>
</section>
<!-- One -->
{% block content %}
{% endblock %}
<!-- Two -->
{% block secondContent %}
{% endblock %}
<!-- Three -->
{% block searchContent %}
{% endblock %}
<!-- Footer -->
<footer id="footer">
<div class="container">
<div class="row double">
<div class="6u">
<div class="row collapse-at-2">
<div class="6u">
<h3>Links</h3>
<ul class="alt">
<li>Link to stuff</li>
<li>Link to stuff</li>
<li>Link to stuff</li>
</ul>
</div>
<div class="6u">
<h3>Links</h3>
<ul class="alt">
<li>Link to stuff</li>
<li>Link to stuff</li>
<li>Link to stuff</li>
</ul>
</div>
</div>
</div>
<div class="6u">
<h2>integrator</h2>
<p>Connecting Sharepoint, Tigerpaw, Appenate,
Teams, and documentation into one interface</p>
</div>
</div>
<ul class="copyright">
<li>© Untitled. All rights reserved.</li>
</ul>
</div>
</footer>
</body>
</html>
searchUpdate.js
$(function() {
$('a#process_input').bind('click', function() {
$.getJSON('/soSearch', {
searchTerm: $('input[name="searchTerm"]').val(),
workType: $('input[name="workType"]:checked').val(),
clientID: $('input[name="acctNumber"]').val(),
}, function(data) {
$("#result").text(data.result);
});
return false;
});
});
related html block for index. held in clientInfo.html ( if it matters all 3 blocks are in this same file)
{% block searchContent %}
<section id="three" class="wrapper style1">
<div class="container">
<div class="row">
<div class="12u">
<section>
<h2>SO Search</h2>
<img src="{{ url_for('static', filename='images/pic03.jpg') }}" alt="" />
<form class="pure-form">
<fieldset>
<p>
<input type="text" placeholder="searchterm" name="searchTerm">
<input type="hidden" name="acctNumber" value="{{ infoItems[0]['AccountNumber'] }}">
<label for="option-one" class="pure-radio">
<input id="option-one" type="radio" name="workType" value="WorkPerformed">
Work Performed
</label>
<label for="option-two" class="pure-radio">
<input id="option-two" type="radio" name="workType" value="WorkRequested">
Work requested
</label>
<a href=# id=process_input><button class='pure-button'>Search</button></a>
</p>
</fieldset>
</form>
<p id=result></p>
</section>
</div>
</div>
</div>
</section>
{% endblock %}
Everything works up until trying to display the returned data. Nothing is shown in
<p id=result></p>
I was using this Python/AJAX as my go to.
Once I click search everything works. I can see in dev tools the json is handed back. Like I said, nothing is shown.
As a secondary question, since I'm passing back a good bit of info the <p> isn't going to work, it's just for testing. Should I assume that if I want to build a dynamic table of returned data that has to be done inside the js as opposed to python since there is no real page refresh?
Turns out the example I was using was wrong. Changed to:
$.getJSON('/soSearch', {
searchTerm: $('input[name="searchTerm"]').val(),
workType: $('input[name="workType"]:checked').val(),
clientID: $('input[name="acctNumber"] option:selected').val(),
}, function(data) {
resultList = '<ul class="alt">';
for ( x in data) {
console.log(data[x]);
resultList += '<li><b>' + x + ' </b> : ' + data[x] + '</li>';
}
resultList += '</ul>';
//console.log(JSON.stringify(data[0][0]));
$('#result').html(resultList);
});
return false;
});
Overall it was the .text to .html that made it display.

Django Project - bootstrap navigation with javascript script not working - Where should JavaScript go?

I have a Django project, in which I have a simple front-end bootstrap horizontal navigation bar (taken from here: https://www.w3schools.com/bootstrap4/tryit.asp?filename=trybs_ref_js_tab_js&stacked=h).
In it, a user clicks on a tab, and it displays the information for that tab, on click.
In this case, I have used django templating language and crispy forms to generate a form inside tab 1. This renders fine, and looks correct in terms of formatting and layout, but, the tabs are not functional. I have looked at other stackoverflow questions, but none are specific to what I am asking.
The functionality of the tabs, I assume, is controlled by the Javascript code snippet:
<script>
$(document).ready(function(){
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
});
</script>
As a newbie to Django and front-end design, I am struggling to see, a) where I have made the mistake and what needs to be corrected in order for the tabs to function correctly on-click. b) how javascript is implemented inside of the whole structure of a Django html template.
By this,I mean, Javascript is usually put inside the 'head' tags, but in this case templates extend a base template in which there is a head, so I am unsure of where Javascript should go. Should I for example, be using external Javascript files in each case? What is best practice? Where should it go in relation to where the "{% blocks" (start and end) go?
A useful answer would
a) point out the error in the code such that my tabs will work
b) explain a little about the layout/structure of where JavaScript snippets go, which add to html/boostrap functionality, inside of a Django-based template and within the framework of using Django Templating language.
The whole code for my profile.html is shown below
{% extends "socialmedia/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{ user.email }}</p>
</div>
</div>
<div class="container mt-3">
<br>
<!-- Nav tabs -->
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link active" href="#home">Tab 1</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#menu1">Tab 2</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#menu2">Tab 3</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#menu3">Tab 4</a>
</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div id="home" class="container tab-pane active"><br>
<h3>Tab 1</h3>
<p>Please fill in your account/profile information here.</p>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Profile Information</legend>
{{u_form|crispy}}
{{p_form|crispy}}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update....</button>
</div>
</form>
</div>
</div>
<div id="menu1" class="container tab-pane fade"><br>
<h3>Tab 2</h3>
<p>Tab 2 information here</p>
</div>
<div id="menu2" class="container tab-pane fade"><br>
<h3>Tab 3</h3>
<p>Tab 3 information will go here</p>
</div>
<div id="menu3" class="container tab-pane fade"><br>
<h3>Calendar</h3>
<p>Manage your Calendar</p>
</div>
</div>
</div>
{% endblock content %}
<script>
$(document).ready(function(){
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
});
</script>
What I've tried: I have tried putting the javascript code in various places - such as before the {% endblock content %} and at the top of the page, but neither has worked.
Update:
I noticed that above the cdn/css hasn't been added. On adding this, it messes up the formatting, and the on-click, sort of works, but not correctly.
The updated code is as below. Again, I'd need suggestions as to where to correctly place this block of code for correct formatting and functionality, as well as the javascript code.
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
Updated profile.html
The following now renders the page incorrectly, moving up the image at the top and the username and email variables in an undesirable fashion. Furthermore, the tabs work, but not completely. The crispy form is generated in each tab, instead of just the first, and the content of the other tabs is shown underneath.
{% extends "socialmedia/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<!--- this code has been added as per the update above -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{ user.email }}</p>
</div>
</div>
<div class="container mt-3">
<br>
<!-- Nav tabs -->
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link active" href="#home">Tab 1</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#menu1">Tab 2</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#menu2">Tab 3</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#menu3">Tab 4</a>
</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div id="home" class="container tab-pane active"><br>
<h3>Tab 1</h3>
<p>Please fill in your account/profile information here.</p>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Profile Information</legend>
{{u_form|crispy}}
{{p_form|crispy}}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update....</button>
</div>
</form>
</div>
</div>
<div id="menu1" class="container tab-pane fade"><br>
<h3>Tab 2</h3>
<p>Tab 2 information here</p>
</div>
<div id="menu2" class="container tab-pane fade"><br>
<h3>Tab 3</h3>
<p>Tab 3 information will go here</p>
</div>
<div id="menu3" class="container tab-pane fade"><br>
<h3>Calendar</h3>
<p>Manage your Calendar</p>
</div>
</div>
</div>
{% endblock content %}
<script>
$(document).ready(function(){
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
});
</script>
I am also including my base template, base.html (which does include a head and a body) below.
{% load static %}
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
{% if title %}
<title>Fakebook Blog Posts - {{title}}</title>
{% else %}
<title>Fakebook Blog</title>
{% endif %}
<!--this is django templating language-->
<link rel="stylesheet" href="{% static 'worldguestbook\main2.css' %}"/>
</head>
<body>
<header class="site-header">
<nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
<div class="container">
<a class="navbar-brand mr-4" href="/">FakeBook Newsfeed</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarToggle">
<div class="navbar-nav mr-auto">
<a class="nav-item nav-link" href="{% url 'socialmedia-home' %}">Home</a>
<a class="nav-item nav-link" href="{% url 'socialmedia-about' %}">About</a>
</div>
<!-- Navbar Right Side -->
<div class="navbar-nav">
{% if user.is_authenticated %}
<a class="nav-item nav-link" href="{% url 'post-create' %}">New Post</a>
<a class="nav-item nav-link" href="{% url 'profile' %}">Profile</a>
<a class="nav-item nav-link" href="{% url 'logout' %}">Logout</a>
{% else %}
<a class="nav-item nav-link" href="{% url 'login' %}">Login</a>
<a class="nav-item nav-link" href="{% url 'register' %}">Register</a>
{% endif %}
</div>
</div>
</div>
</nav>
</header>
<main role="main" class="container">
<div class="row">
<div class="col-md-8">
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{message.tags}}">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% block content %}{% endblock %}
</div>
<div class="col-md-4">
<div class="content-section">
<h3>Our Sidebar</h3>
<p class='text-muted'>You can put any information here you'd like.
<ul class="list-group">
<li class="list-group-item list-group-item-light">Latest Posts</li>
<li class="list-group-item list-group-item-light">Announcements</li>
<li class="list-group-item list-group-item-light">Calendars</li>
<li class="list-group-item list-group-item-light">etc</li>
</ul>
</p>
</div>
</div>
</div>
</main>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
I came across a possible answer (not on stackoverflow) which suggested, that adding a DTL block in the base template like this:
{% block extra_js %}{% endblock extra_js %}
and then adding the script inside those tags in the profile.html page, would work, but it hasn't either. (see below addition that I've tried)
added to the base.html...
<body>
{% block extra_js %}{% endblock extra_js %}
<header class="site-header">
<nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
<div class="container">
in the profile.html ....
<h3>Calendar</h3>
<p>Manage your Calendar</p>
</div>
</div>
</div>
{% block extra_js %}
<script>
$(document).ready(function(){
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
});
</script>
{% endblock extra_js %}
{% endblock content %}
The above, doesn't work at all.
But, on adding even more additional blocks to the base, and then adding the css in those blocks in the profile.html, the same problem as described above occurs. (tabs are clickable, but the form content is shown in all of them, and also the tab content is generated at the bottom like an overflow).
To clarify, the below is added to profile.html
{% block extra_css %}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
{% endblock extra_css %}
with this added to base.html (in the head)
<head>
{% block extra_css %}{% endblock extra_css %}

JavaScript element issue in Twig template with Symfony 2

I have an issue with Javascript elements in my twig template.
JS carousel element on top of the page is not loading when href path when site menu is changed from a id style reference (e.g href = "#terms") to link to a different page (e.g href={{ path('terms') }}.
This is my part of index.html.twig
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> {% block title %} Test Script {% endblock %}</title>
<link rel="shortcut icon" href="{{ asset('favicon.ico') }}"/>
{% block stylesheets %}
{% stylesheets 'bundles/useruser/css/*' filter='cssrewrite' %}
<link rel="stylesheet" href="{{ asset_url }}" type="text/css"/>
{% endstylesheets %}
{% endblock %}
<script type="text/javascript" charset="utf-8" src="//code.jquery.com/jquery-2.1.4.min.js"></script>
{% block javascripts %}
{% javascripts '#UserUserBundle/Resources/public/js/*' %}
<script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
{% endblock %}
</head>
<body>
{% block body %}
<div id="sTop" class="site-main">
<div class="site-header">
<div class="main-header">
<div class="container">
<div id="menu-wrapper">
<div class="row">
<div class="logo-wrapper col-md-4 col-sm-2 col-xs-8">
<h1>
<a>Travel Flex</a>
</h1>
</div>
<div class="col-md-8 col-sm-10 col-xs-4 main-menu text-left">
<ul class="menu-first hidden-sm hidden-xs">
<li class="active">{{ 'About' }}</li>
<li>{{ 'Terms & Conditions' }}</li>
<li>{{ 'Privacy Policy' }}</li>
<li>{{ 'Subscribe' }}</li>
<li>{{ 'Unsubscribe' }}</li>
</ul>
<i class="fa fa-bars"></i>
</div>
</div>
</div>
<div class="menu-responsive hidden-md hidden-lg">
<ul>
<li class="active">{{ 'About' }}</li>
<li>{{ 'Terms & Conditions' }}</li>
<li>{{ 'Privacy Policy' }}</li>
<li>{{ 'Subscribe' }}</li>
<li>{{ 'Unsubscribe' }}</li>
</ul>
</div>
</div>
</div>
</div>
<div class="site-slider">
<div class="slider">
<div class="flexslider">
<ul class="slides">
<li>
<div class="overlay"></div>
<img src="{{ asset('bundles/useruser/images/slide1.jpg') }}" alt="">
<div class="slider-caption visible-md visible-lg">
<h2>test text 1</h2>
<p>test text 1</p>
</div>
</li>
<li>
<div class="overlay"></div>
<img src="{{ asset('bundles/useruser/images/slide2.jpg') }}" alt="">
<div class="slider-caption visible-md visible-lg">
<h2>test text2</h2>
<p>test text 2</p>
</div>
</li>
<li>
<div class="overlay"></div>
<img src="{{ asset('bundles/useruser/images/slide3.jpg') }}" alt="">
<div class="slider-caption visible-md visible-lg">
<h2>test text 3</h2>
<p>test text 3</p>
</div>
</li>
</ul>
</div> <!-- /.flexslider -->
</div> <!-- /.slider -->
</div> <!-- /.site-slider -->
</div> <!-- /.site-main -->
Carousel element is loading fine when i use href = "#terms".
However link does not work as it should (links in red rectangular not redirecting to a different page).
When i use href={{ path('terms') }} link works as it should, however carousel element is not loaded.
Looks like there is an issue with how i include js files into index.html.twig however i am not sure how to fir it. Below is the error from browser console:
Any assistance is appriciated
Replace the Include jQuery Library Code Snippet like below
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
Checkout other jQuery CDN or save the file to your server.
http://www.w3schools.com/jquery/jquery_get_started.asp
Add Absolute URL for your Slider images
{{ absolute_url(asset('bundles/useruser/images/slide1.jpg')) }}

Categories