I've created a add-to-cart in my website and it works just great.
Am using Jquery.getJSON to make the request to get the value of the chosen product, here is the code:
$(function() {
$('a#process_menu').bind('click', function() {
/*var amount = document.getElementById('kale').value;*/
$.getJSON('{{url_for("get_the_order")}}', {
menu_order: $(this).text(), price_order: $('input[name="kalkal"]').val(),
}, function(data) {
location.reload();
});
return false;
});
});
and here is the function that receiving the request:
#app.route('/get_the_order')
def get_the_order():
global the_order_list
try:
the_order_list = []
sum_list = []
get_order = request.args.get('menu_order', 0, type=str)
get_price = request.args.get('price_order', 0, type=str)
the_order_list.append(get_order)
sum_list.append(get_price)
session['theOrder'] = ' '.join(the_order_list)
session['price'] = ' '.join(sum_list)
return jsonify(result=the_order_list + sum_list)
except Exception as e:
return redirect("menu")
and here i have the template that shows all the products:
{% if entries_menu %}
{% for menu_ent in entries_menu %}
<div class="col-sm-6 col-md-3 col-lg-3 {{menu_ent.categorie}}">
<div class="portfolio-item">
<div class="hover-bg">
<a id="process_menu">
<div class="hover-text">
<h4 id="title">{{menu_ent.title}}</h4>
<small id="price">{{menu_ent.price}}</small>
<div class="clearfix"></div>
<i class="fa fa-plus add_basket"></i>
<div class="counter-order">
<div class="row">
<div class="col-md-3">
<form>
<fieldset>
<div class="form-group">
<input id="kale" name="kalkal" class="form-control" type="number" value="1" min="1" max="999" />
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
<img src="../../static/{{menu_ent.path}}" class="img-responsive" alt="..." id="image-menu">
</a>
</div>
<h4 class="brand bold">{{menu_ent.title}}</h4>
<span class="price pull-right">{{menu_ent.price}} </span><span class="amount pull-right"> {{menu_ent.amount}}</span>
<p id="descr">{{menu_ent.descr}}</p>
</div>
</div>
{% endfor %}
{% endif %}
here i made this function to put all the products within array and showing them above where the cart exist beside the header, this is the file where all the logic happens also where it should show what i want:
{% if session.logged_in %}
{% if session.theOrder %}
<div class="confirm-cancel">
<i class="fa fa-close fa-3x btn-danger"></i>
<i class="fa fa-check fa-3x btn-success"></i>
</div>
{% endif %}
<li class='main'><a href='/#main'><span>Main</span></a></li>
<li class="comfort"><a href='/#ckidki' ><span>Chief</span></a></li>
<li class="menu"><a href='/menu/' ><span>Menu</span></a></li>
<li class="order"><a href="/order/" ><span>Make an order</span></a></li>
<li class="contact"><a href='/#contact' ><span>Contact us</span></a></li>
<li class="last orders"><a href='/admin/' ><span>Admin</span></a></li>
{% if session.theOrder %}
<li class="basket"><i class="fa fa-shopping-basket fa-3x" style="color: #fff;"><p class="pull-left" id="bask" style="font-size: 19px; font-weight: 600; font-family: "Russo One",sans-serif;">{{session.get('theOrder')}}  x{{session.get('price')}}</p></i></li>
{% else %}
<li class="basket"><i class="fa fa-shopping-basket fa-3x" style="color: #fff;"><p class="pull-left" id="bask" style="font-size: 19px; font-weight: 600; font-family: "Russo One",sans-serif;">0$   </p></i></li>
{% endif %}
{% endif %}
The problem is i can't get all the products that i've been chosen inside the session, so if i checked the products list i see only one, in fact , am getting only the clicked item every time.
Please, any suggestion how to make that work, anyway please, any help would be tons appreciated .
I modified your code like this:
the_order_list = session['theOrder']
sum_list = session['price']
the_order_list.append(get_order)
sum_list.append(get_price)
session['theOrder'] = the_order_list
session['price'] = sum_list
I was facing the same issue and finally got this answer!
#app.route('/addtocart/') #加入购物车选项
def addtocart():
id = request.args.get('id')
if 'cart' not in session:
session['cart'] = [] #
cart_list = session['cart']
cart_list.append(id)
session['cart'] = cart_list #
print(session)
cart_list = session['cart'] will return an empty list. Then, after cart_list.append(id), you've got a list with length 1. The key sentence is session['cart'] = cart_list, if you don't do this, your list's maximum length is 2.
Related
I am unable to deploy django in Heroku. I think the problem lies with Ajax because all of the pages seems to render in heroku.
Error that I got is:
InvalidCursorName at /incidentReport/general
cursor "_django_curs_140297876031040_sync_1" does not exist
During handling of the above exception (relation "incidentreport_accidentcausation" does not exist LINE 1: ...cidentreport_accidentcausation"."updated_at" FROM "incidentr... ^ ), another exception occurred:
Thank you
HTML
<!-- Page Content -->
<div class="container-fluid">
<!-- Page Title -->
<div class="d-flex bd-highlight">
<div class="pg-title p-2 flex-grow-1 bd-highlight">
<h4>Incident Report</h4>
</div>
</div>
<!-- User Report Table -->
<div class="card shadow mb-5 d-flex ">
<!-- Top Pagination -->
<div class="card-header py-3">
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link active" href="{% url 'incident_report_general' %}">General</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'incident_report_people' %}">People</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'incident_report_vehicle' %}">Vehicle</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'incident_report_media' %}">Media</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'incident_report_remarks' %}">Remarks</a>
</li>
</ul>
</div>
<div class="card-body">
<div class="table-responsive">
<table>
<form id="form_incidentgeneral" action="{% url 'incident_report_general' %}" enctype="multipart/form-data" method="post" data-acc-url="{% url 'ajax_load_accident' %}">
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Date</label>
{{user_report_form.date}}
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Time</label>
{{user_report_form.time}}
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputAddress">Street Address</label>
{{user_report_form.location}}
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputWeather">Weather</label>
{{inc_gen_form.weather}}
</div>
<div class="form-group col-md-6">
<label for="inputLight">Light</label>
{{inc_gen_form.light}}
</div>
</div>
<!-- ================================= -->
<hr>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputSeverity">Severity</label>
{{inc_gen_form.severity}}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputAccident">Accident Factor</label>
{{inc_gen_form.accident_factor}}
</div>
<div class="form-group col-md-6">
<label for="inputAccident">Accident Factor Sub Category</label>
{{inc_gen_form.accident_subcategory}}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputAccident">Collision Type</label>
{{inc_gen_form.collision_type}}
</div>
<div class="form-group col-md-6">
<label for="inputAccident">Collision Sub Category</label>
{{inc_gen_form.collision_subcategory}}
</div>
</div>
<!-- ================================= -->
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputCrashType">Crash Type</label>
{{inc_gen_form.crash_type}}
</div>
<div class="form-group col-md-6">
<label for="inputMovement">Movement Code</label>
{{ inc_gen_form.movement_code }}
</div>
</div>
<!-- ================================= -->
<br>
<div class="modal-footer mb-3">
<input type="button" class="btn btn-secondary" data-dismiss="modal"
value="Clear">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</form>
</table>
</div>
</div>
</div>
<!-- End of User Report Table -->
</div>
<!-- End of Page Content -->
AJAX
<script>
$("#id_accident_factor").change(function () {
const url = $("#form_incidentgeneral").attr("data-acc-url"); // get the url of the `load_cities` view
const accidentId = $(this).val(); // get the selected country ID from the HTML input
$.ajax({ // initialize an AJAX request
url: url, // set the url of the request (= /persons/ajax/load-cities/ )
data: {
'accident_factor_id': accidentId // add the country id to the GET parameters
},
success: function (data) {
//console.log(data) // `data` is the return of the `load_cities` view function
$("#id_accident_subcategory").html(data); // replace the contents of the city input with the data that came from the server
let html_data = '<option value="">---------</option>';
data.forEach(function (accident_subcategory) {
html_data += `<option value="${accident_subcategory.id}">${accident_subcategory.sub_category}</option>`
});
console.log(html_data);
$("#id_accident_subcategory").html(html_data);
}
});
});
$("#id_collision_type").change(function () {
const url = $("#form_incidentgeneral").attr("data-acc-url"); // get the url of the `load_cities` view
const collisionId = $(this).val(); // get the selected country ID from the HTML input
$.ajax({ // initialize an AJAX request
url: url, // set the url of the request (= /persons/ajax/load-cities/ )
data: {
'collision_type_id': collisionId // add the country id to the GET parameters
},
success: function (data) {
//console.log(data) // `data` is the return of the `load_cities` view function
$("#id_collision_subcategory").html(data); // replace the contents of the city input with the data that came from the server
let html_data = '<option value="">---------</option>';
data.forEach(function (collision_subcategory) {
html_data += `<option value="${collision_subcategory.id}">${collision_subcategory.sub_category}</option>`
});
console.log(html_data);
$("#id_collision_subcategory").html(html_data);
}
});
});
</script>
Dropdown HTML
<option value="">---------</option>
{% for accsubcategory in acc_subcat %}
<option value="{{ accsubcategory.pk }}">{{ accsubcategory.sub_category }}</option>
{% endfor %}
{% for colsubcategory in col_subcat %}
<option value="{{ colsubcategory.pk }}">{{ colsubcategory.sub_category }}</option>
{% endfor %}
Views
def incident_report_general(request):
if request.method == 'POST':
user_report_form = UserReportForm(request.POST, request.FILES)
inc_gen_form = IncidentGeneralForm(request.POST, request.FILES)
else:
user_report_form = UserReportForm()
inc_gen_form = IncidentGeneralForm()
context = {
'user_report_form': user_report_form,
'inc_gen_form': inc_gen_form,
}
return render(request, 'pages/incident_report.html', context)
def load_accident(request):
accident_factor_id = request.GET.get('accident_factor_id')
collision_type_id = request.GET.get('collision_type_id')
acc_subcat = AccidentCausationSub.objects.filter(accident_factor_id=accident_factor_id).all()
col_subcat = CollisionTypeSub.objects.filter(collision_type_id=collision_type_id).all()
context = {
'acc_subcat': acc_subcat,
'col_subcat': col_subcat
}
return render(request, 'incident/acc_sub_dropdown_list_options.html', context)
Form
class IncidentGeneralForm(forms.ModelForm):
class Meta:
model = IncidentGeneral
fields = '__all__'
def __init__(self, *args, **kwargs):
super(IncidentGeneralForm, self).__init__(*args, **kwargs)
self.fields['accident_factor'].widget.attrs['class'] = 'form-control'
self.fields['accident_subcategory'].widget.attrs['class'] = 'form-control'
self.fields['collision_type'].widget.attrs['class'] = 'form-control'
self.fields['collision_subcategory'].widget.attrs['class'] = 'form-control'
self.fields['weather'].widget.attrs['class'] = 'form-control'
self.fields['light'].widget.attrs['class'] = 'form-control'
self.fields['severity'].widget.attrs['class'] = 'form-control'
self.fields['crash_type'].widget.attrs['class'] = 'form-control'
self.fields['movement_code'].widget.attrs['class'] = 'form-control'
self.fields['accident_subcategory'].queryset = AccidentCausationSub.objects.none()
self.fields['collision_subcategory'].queryset = CollisionTypeSub.objects.none()
if 'accident_factor' in self.data:
try:
accident_factor_id = int(self.data.get('accident_factor'))
self.fields['accident_subcategory'].queryset = AccidentCausationSub.objects.filter(accident_factor_id=accident_factor_id).order_by('accident_factor')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['accident_subcategory'].queryset = self.instance.accident_factor.accident_subcategory_set.order_by('subcategory')
if 'collision_type' in self.data:
try:
collision_type_id = int(self.data.get('collision_type'))
self.fields['collision_subcategory'].queryset = CollisionTypeSub.objects.filter(collision_type_id=collision_type_id).order_by('collision_type')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['collision_subcategory'].queryset = self.instance.collision_type.collision_subcategory_set.order_by('subcategory')
I'm trying to create a table of records to update with a single click. I keep getting the error [{'id': ['This field is required.']}] I can't seem to figure it out. I have tried to put {{ form.label_tag }} in somewhere to see if that would help, but it doesn't. I can't figure out how to be sure id gets passed back in for the edit.
forms.py
class ReleaseAssignForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ReleaseAssignForm, self).__init__(*args, **kwargs)
for key in self.fields:
self.fields[key].required = False
class Meta:
model = Releases
fields = [
'id',
'rel_title',
'rel_summary',
'rel_english_title',
'rel_english_summary',
'rel_country',
'rel_risk_category',
'rel_ops_category',
'rel_assoc_indicator',
'rel_industry',
'rel_risk_assigned',
'rel_ops_assigned',
'rel_indu_assigned',
'rel_indi_assigned',
]
views.py
def preview_releases(request):
today = datetime.date.today()
count = 0
releases = Releases.published.filter(rel_date=today)
ReleaseAssignFormSet = modelformset_factory(Releases, ReleaseAssignForm, fields = '__all__', extra=0)
if request.method == "POST":
formset = ReleaseAssignFormSet(request.POST, queryset=releases)
if formset.is_valid():
posts = formset.save(commit=False)
for post in posts:
post.save()
return redirect('preview_releases')
else:
print(formset.errors)
print("Form Invalid")
else:
formset = ReleaseAssignFormSet(queryset=releases)
count = formset.total_form_count()
context = {
'count': count,
'formset': formset,
}
return render(request, 'management/preview-releases.html', context)
template.html
<form action="" method="POST">
{% csrf_token %}
{{ formset.management_form }}
{% if formset %}
{% for form in formset.forms %}
<div class="row py-5" style="border-bottom: 1px black solid;font-size: 14px;">
<div class="row px-5 pb-2" style="border-bottom: 1px lightgray dotted;font-size: 14px;">
<div class="col px-5 pb-2">
<span style="font-size: 12px;color: darkred;">Risk Category</span><br>
{{ form.rel_risk_category }}
</div>
<div class="col px-5 pb-2" style="border-right: 1px darkgray dotted;">
<span style="font-size: 12px;color: darkred;">Assigned</span><br>
{{ form.rel_risk_assigned }}
</div>
<div class="col px-5 pb-2">
<span style="font-size: 12px;color: darkred;">Ops Category</span><br>
{{ form.rel_ops_category }}
</div>
<div class="col px-5 pb-2">
<span style="font-size: 12px;color: darkred;">Assigned</span><br>
{{ form.rel_ops_assigned }}
</div>
</div>
<div class="row px-5 pt-2 pb-5">
<div class="col px-5 pb-2">
<span style="font-size: 12px;color: darkred;">Associated Indicator</span><br>
{{ form.rel_assoc_indicator }}
</div>
<div class="col px-5 pb-2" style="border-right: 1px darkgray dotted;">
<span style="font-size: 12px;color: darkred;">Assigned</span><br>
{{ form.rel_indi_assigned }}
</div>
<div class="col px-5 pb-2">
<span style="font-size: 12px;color: darkred;">Industry</span><br>
{{ form.rel_industry }}
</div>
<div class="col px-5 pb-2" >
<span style="font-size: 12px;color: darkred;">Assigned</span><br>
{{ form.rel_indu_assigned }}
</div>
</div>
<div class="row">
<div class="col px-5">
<h3>{{ form.instance.rel_title }}</h3>
<p>{{ form.label_tag }}</p>
<p>{{ form.instance.rel_summary }}</p>
</div>
<div class="col px-5" style="border-left: 1px lightgray dashed;">
<a target="_blank" href="{% url 'clean_release' form.instance.id %}"><h3>{{ form.instance.rel_title }}</h3></a>
<p>{{ form.instance.rel_country }}</p>
{% autoescape off %}
<p>{{ form.instance.rel_summary }}</p>
{% endautoescape %}
</div>
<div class="col px-5" style="border-left: 1px lightgray dashed;">
<a target="_blank" href="{% url 'clean_release' form.instance.id %}"><h3>{{ form.instance.rel_english_title }}</h3></a>
<p>{{ form.instance.rel_country }}</p>
{% autoescape off %}
<p>{{ form.instance.rel_english_summary }}</p>
{% endautoescape %}
</div>
</div>
</div>
{% endfor %}
{% else %}
No resources found.
{% endif %}
<div class="text-end py-5">
<button type="submit" class="btn btn-primary">Submit Changes</button>
</div>
</div>
</form>
I am using bootstrap tabs navigation bar and I want to retrieve the id of the tag and pass it to my view but my main issue though is I am not using them in my urls.py. Here is my urls.py file.
from django.urls import path
from .views import (
index, add_task, update_task,
delete_task, update_categories,
delete_all_task
)
urlpatterns = [
path('', index, name="home"),
path('add-task/', add_task, name="add-task"),
path('update-task/<int:pk>/', update_task, name="update-task"),
path('delete-task/<int:pk>/', delete_task, name="delete-task"),
path('update-category/', update_categories, name="update-category"),
path('delete_all_tasks/', delete_all_task, name="delete_all_tasks"),
]
And here is the views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.forms import modelformset_factory
from .models import Tasks, Category
from .forms import AddTaskForm, UpdateTaskForm, UpdateCategoryForm
def get_task_minid(categories):
id_list = []
for task in categories:
id_list.append(task.id)
min_id = min(id_list)
return min_id
def index(request):
tasks = Tasks.objects.all()
categories = Category.objects.all()
if len(categories) > 1:
min_id = get_task_minid(categories)
if request.method == "POST":
category = request.POST.get('category')
cat = Category.objects.create(name=category)
cat.save()
return redirect('home')
context = {
'tasks': tasks,
'categories': categories,
'min_id': min_id,
}
return render(request, 'Todo/index.html', context)
and here is the index.HTML
<div class="" id="Todo-tasks">
<div class="card card-primary card-outline">
<div class="card-body">
<div class="row">
<div class="col-5 col-sm-3">
<div class="card-header">
<span>All Categories</span>
</div>
<div class="nav flex-column nav-tabs h-100" id="vert-tabs-tab" role="tablist" aria-orientation="vertical">
{% for cat in categories %}
{% if cat.id == min_id %}
<a class="nav-link active" id="vert-tabs-{{cat}}-tab" data-toggle="pill" href="#vert-tabs-{{cat}}"
role="tab" aria-controls="vert-tabs-{{cat}}" aria-selected="true">{{cat}}</a>
{% else %}
<a class="nav-link" id="vert-tabs-{{cat}}-tab" data-toggle="pill" href="#vert-tabs-{{cat}}"
role="tab" aria-controls="vert-tabs-{{cat}}" aria-selected="false">{{cat}}</a>
{% endif %}
{% endfor %}
<div class="card-footer mt-3">
<form action="" method="POST">
{% csrf_token %}
<input type="text" name="category" placeholder="Add category" class="new-input cat" aria-label="Add new category" />
<button type="submit" class="new">+</button>
</form>
</div>
Manage Categories
</div>
</div>
<div class="col-7 col-sm-9">
<div class="tab-content" id="vert-tabs-tabContent">
{% for cat in categories %}
{% if cat.id == min_id %}
<div class="tab-pane text-left fade show active" id="vert-tabs-{{cat}}" role="tabpanel" aria-labelledby="vert-tabs-{{ cat }}-tab">
<ul class="list-unstyled border pb-4">
<div class="card-header d-flex justify-content-between justify-content-center">
{{ cat }}
<div class="form-group">
<form action="" class="p-0 justify-content-end" method="post">
<input type="text" name="search" class="form-input pl-3" placeholder="Search for tasks..."/>
</form>
</div>
</div>
{% for task in cat.tasks.all %}
<li class="align-content-center"><a>{{task.text}}
<small class="badge bg-success">{{task.due_date|timeuntil|upto:','}}</small>
<span class=""></i></span>
<span class=""></i></span>
</a>
</li>
{% empty %}
<h3 class="alert alert-info m-5"><i class="fas fa-alert-outline"></i> Please add new tasks to categories</h3>
{% endfor %}
</ul>
</div>
{% else %}
<div class="tab-pane text-left fade show" id="vert-tabs-{{cat}}" role="tabpanel" aria-labelledby="vert-tabs-{{ cat }}-tab">
<ul class="list-unstyled border pb-4">
Now, how I am thinking of a way to get the h ref in the like(h ref="vert-tabs-{{cat}}" I want to get the value of the cat variable anytime I switch to a different sort of view or tab content.
Any help would be so appreciated even JavaScript or j query.
Thank you in advance...
I am working on a PRoject and I am stuck on order page.
Here, I want to display list of product images in options tag so that a user can select one image from all or can upload an image functionality of uploading image is working correctly but the selection is not working.
I want to show images to user so that user can select one of them.
models.py
class Product(models.Model):
prod_ID = models.AutoField("Product ID", primary_key=True)
prod_Name = models.CharField("Product Name", max_length=30, null=False)
prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
prod_img = models.ImageField("Product Image", null=True)
class ImageTemplate(models.Model):
temp_id = models.AutoField("Template ID", primary_key=True, auto_created=True)
temp_img = models.ImageField("Template Image", null=False)
class ImageTemplateProductMapping(models.Model):
imageTemp_p_map_id = models.AutoField("Template Image & Product Map ID", primary_key=True, auto_created=True)
temp_id = models.ForeignKey(ImageTemplate, null=False, on_delete=models.CASCADE,
verbose_name="Image Template ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
views.py
def order(request, id):
products = Product.objects.all()
ImageTemplateProductsList = []
try:
ImageTemplateProductsMap = ImageTemplateProductMapping.objects.filter(prod_id=id)
ImageTemplateProductsList = [data.temp_id.temp_img for data in
ImageTemplateProductsMap]
except AttributeError:
pass
context = {'products': products,
"ImageTemplateProductsList": ImageTemplateProductsList
}
return render(request, 'user/order.html', context)
order.html
{% extends 'user/layout/userMaster.html' %}
{% block title %}Order{% endblock %}
{% block css %}
form
{
position:relative;
}
.tasksInput
{
margin-right:150px;
}
label
{
vertical-align: top;
}
{% endblock %}
{% block header %}
{% endblock %}
{% block main %}
<div class="container">
<div>
<div class="row rounded mx-auto d-block d-flex justify-content-center">
<button class="btn btn-secondary my-2 mr-1">Custom</button>
<button class="btn btn-secondary my-2 ml-1">Package</button>
</div>
<div class="row">
<div class="col-4">
<div class="card border border-secondary">
<div class="card body mx-2 mt-4 mb-2">
{% for product in products %}
<a id="{{ product.prod_ID }}" class="card-header" style="font-size:5vw;color:black;"
href="{% url 'user-order' product.prod_ID %}">
<h5 class="h5">{{ product.prod_ID }}. {{ product.prod_Name }}</h5></a>
<div class="dropdown-divider"></div>
{% endfor %}
</div>
</div>
</div>
<div class="col-8">
<form>
<div class="card mx-2 my-2 border border-secondary">
<div class="my-2">
<div class="form-group">
<div class="form-group row mx-2">
<label for="quantity"
class="form-control-label font-weight-bold card-header col-4 ml-4 my-auto"
style="background-color:#e3e4e6"><h5>Quantity : </h5></label>
<input id="quantity" class="form-control col-5 mx-2 my-auto" type="number">
</div>
</div>
<div class="form-group">
<div class="form-group row mx-2">
<label for="ImageTemplateProductsList"
class="form-control-label font-weight-bold card-header col-4 ml-4"
style="background-color:#e3e4e6"><h5>Image Template : </h5></label>
<div id="ImageTemplateProductsList" class="mx-2">
<input id="Upload" type="radio" name="ImageSelection" value="Upload"/> Upload an
Image
<input type="file" name="file" class='btn btn-outline-secondary type my-2'>
<br>
<input id="Select" type="radio" name="ImageSelection" value="Select"/> Select
From Templates
<!-- Button trigger modal -->
<input type="button" name="url" style='display: none;'
class='btn btn-outline-secondary type my-2'
value="Choose Template" data-toggle="modal"
data-target="#exampleModalLong">
<!-- Modal -->
<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Select
Template</h5>
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="d-flex-row justify-content-center modal-body"
style="background:red;">
<div>
<!-- Here I want to display images in select tag to make selection of one from all images but not able to achieve it. -->
<select id="ImageTemplateProductsList1">
{% for IT in ImageTemplateProductsList %}
<option value="{{IT}}"
><img src="{{IT.url}}" height="250" width="400"
class="border border-secondary rounded my-2 mx-3">
</option>
<br>
{% endfor %}
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-danger"
data-dismiss="modal">Close
</button>
<button type="button" class="btn btn-outline-secondary">
Select
</button>
</div>
</div>
</div>
</div>
<br>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<div class="row rounded mx-auto d-block d-flex justify-content-center">
<button class="btn btn-success my-2">Place Order</button>
</div>
</div>
</div>
{% endblock %}
{% block js %}
$("document").ready(function(){
$(".type").hide();
$("input:radio").change(function() {
$(".type").hide();
$(this).next("input").show();
});
});
{% endblock %}
urls.py
path('order/<int:id>', views.order, name="user-order"),
I have slightly modified my html template with jquery and changed views a little bit and now it is working for me.
order.html
{% extends 'user/layout/userMaster.html' %}
{% block title %}Order{% endblock %}
{% block css %}
.t {
display: none;
}
img:hover {
opacity:0.8;
cursor: pointer;
}
img:active {
opacity:0.5;
cursor: pointer;
}
input[type=radio]:checked + label > img {
border: 20px solid rgb(228, 207, 94);
}
#dropdown{
height: 50px;
width: 50%;
font-size: 20px;
margin-left: 10px;
margin-top: 3px;
}
{% endblock %}
{% block header %}
{% endblock %}
{% block main %}
<div class="container">
<div>
<div class="row rounded mx-auto d-block d-flex justify-content-center">
<button class="btn btn-secondary my-2 mr-1">Custom</button>
<button class="btn btn-secondary my-2 ml-1">Package</button>
</div>
<div class="row">
<div class="col-4">
<div class="card border border-secondary">
<div class="card body mx-2 mt-4 mb-2">
{% for product in products %}
<a id="{{ product.prod_ID }}" class="card-header" style="font-size:5vw;color:black;"
href="{% url 'user-order' product.prod_ID %}">
<h5 class="h5">{{ product.prod_ID }}. {{ product.prod_Name }}</h5></a>
<div class="dropdown-divider"></div>
{% endfor %}
</div>
</div>
</div>
<div class="col-8">
<form method="POST" enctype="multipart/form-data">
<input type="hidden" id="templateValue" name="templateValue" value=""/>
{% csrf_token %}
<div class="form-group">
<div class="form-group row mx-2">
<label for="ImageTemplateProductsList"
class="form-control-label font-weight-bold card-header col-4 ml-4"
style="background-color:#e3e4e6"><h5>Image Template : </h5></label>
<div id="ImageTemplateProductsList" class="mx-2">
<input id="Upload" type="radio" name="ImageSelection"
class="templateSelection"/> Upload an
Image
<div class="type">
<input type="file" name="image"
class='btn btn-outline-secondary my-2 SelectedImage'>
</div>
<br>
<input type="radio" id="Select" name="ImageSelection" class="templateSelection"
/> Select
From Templates
<div class="type">
{% for IT in ImageTemplateProductsList %}
<input type="radio" name="image2" id="{{IT}}"
value="{{IT}}" class="SelectedImage t"/>
<label for="{{IT}}">
<img src="{{IT.url}}" style="width: 20vw;
height: 20vw;
padding: 2vw;"/>
</label>
<br>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row rounded mx-auto d-block d-flex justify-content-center">
<button type="submit" class="btn btn-success my-2">Place Order</button>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
{% block js %}
$("document").ready(function(){
$(".type").hide();
$("input:radio").on('change', function() {
$(".type").hide();
$(this).next("div").show();
});
$("#templateValue").val('');
$(".templateSelection").on('change', function(){
$("#templateValue").val('');
$("#templateValue").val($(this).attr('id'));
console.log($("#templateValue").val());
});
});
{% endblock %}
I have used hidden field to check whether user is trying to upload the image or select tha image and according to that I am taking the decision that what should I do:
views.py
def order(request, id):
products = Product.objects.all()
ImageTemplateProductsList = []
try:
ImageTemplateProductsMap = ImageTemplateProductMapping.objects.filter(prod_id=id)
ImageTemplateProductsList = [data.temp_id.temp_img for data in
ImageTemplateProductsMap]
except AttributeError:
pass
if request.method == 'POST':
try:
if request.POST['templateValue'] == 'Upload':
if 'image' in request.FILES:
Template_Value1 = request.FILES['image']
fs = FileSystemStorage()
fs.save(Template_Value1.name, Template_Value1)
TemplateValue = Template_Value1.name
elif request.POST['templateValue'] == 'Select':
TemplateValue = request.POST['image2']
else:
pass
except MultiValueDictKeyError:
pass
order_store = Order(product_img=TemplateValue)
order_store.save()
context = {'products': products,
"ImageTemplateProductsList": ImageTemplateProductsList
}
return render(request, 'user/order.html', context)
the problems is i have passing data from view to product template , when i click add to cart i have to get product id accordingly using js how can i do this inside templates it work but when i apply inside script it doesn't work is there any method to access / get data
my views.py
def product(request):
productbyid = None
categories = ProductCategory.get_all_categories()
products = TopList.get_all_products()
categoryID = request.GET.get('category')
if categoryID:
productbyid =TopList.objects.filter(category=categoryID)
else:
productbyid = TopList.get_all_products()
data = {}
data['categories']:categories
data['productbyid'] =productbyid
data['products'] = products
data['categories'] =categories
return render(request,'product.html',data)
my product.html
% for pbyid in productbyid %}
<div class="card card_body m-2 p-0 container" id='{{pbyid.id}}'>
<div>
<div>
<div class='imagestyle' ><img class="card-img-top " src="{{pbyid.image}}"width="500" height="200" alt="Card image cap "></div>
<span class="top-left">{{pbyid.discountpercentage}}% off</span>
</div>
<div class="card-body">
<h5 class="card-title cardtitle">{{pbyid.title}}</h5>
<div><p class="carddesccrip">{{pbyid.desc}} </p></div>
<div class='pricce_card'>
<span class='price'> <b>M.R.P</b> <strike class='carddesc'>RS {{pbyid.discountPrice}}</strike></span>
<span class='final_price'><b>RS. {{pbyid.finalprice}}</b></span>
</div>
</div>
<div class="card-body">
{% comment %} /viewpage/{{pbyid.id}} {% endcomment %}
<button href="" class="btn btn-lg btn-block addbtn caddtocart" onclick="myFunction()" > Add to cart {{pbyid.id}}
<i class="fa fa-plus float-right align-center p-2 plusbtn" aria-hidden="true"></i></button>
</div>
</div>
</div>
{% endfor %}
js , my try here i when i click caddtocart btn i have to get product id accordingly but it doesn't work .
<script>
var x = document.getElementsByClassName("caddtocart");
function myFunction() {
d = "{{products}}";
data = parseInt(d);
console.log(data);
}
</script>
you can pass variables from a template to JS like so:
onclick="myfunction({{pbyid.id}})"
this will pass the id to the function for you then in your js you get the parameter like:
myfunction(id){}