How to sum the list in template django? - python

I want to get the sum of the moneylog_set.price
so i try to assign total_pay but the error occur
view.py
def all_moneybooks(request):
current_user = request.user
if current_user.is_authenticated:
current_user_moneybooks = current_user.owner.all()
total_pay = 0
book_total_pay_list = []
for current_user_moneybook in current_user_moneybooks:
moneylog_set = current_user_moneybook.moneylog_set.all()
for moneylog in moneylog_set:
total_pay += moneylog.price
book_total_pay_list.append(
(moneylog.moneybook.id, moneylog.price))
print(dir(moneylog_set))
print(book_total_pay_list)
return render(request, "home.html", context={"current_user": current_user, "all_moneybooks": all_moneybooks, "current_user_moneybooks": current_user_moneybooks, "total_pay": total_pay, "book_total_pay_list": book_total_pay_list})
else:
return render(request, "home.html", context={"current_user": current_user, "all_moneybooks": all_moneybooks})
home.html
{% for current_user_moneybook in current_user_moneybooks %}
<a href="{% url "moneybooks:detail" current_user_moneybook.pk %}">
<div class="border-gray-400 border-t border-b border-l border-r">
<div class="container flex mx-auto">
<div class="w-1/5 my-10">
<p class="text-center text-gray-900">{{current_user_moneybook.country}}</p>
</div>
<div class="w-3/5 my-3">
<div class="inline-block align-middle text-gray-900 font-bold text-xl mb-2">{{current_user_moneybook.name}}</div>
<div class="text-gray-700 text-sm">{{current_user_moneybook.companion.all}}</div>
<div class="text-gray-900 text-sm">{{current_user_moneybook.start_date|date:"Y년 m월 d일"}} ~ {{current_user_moneybook.end_date|date:"Y년 m월 d일"}}</div>
</div>
<div class="w-1/5 my-10">
<div class="text-center text-gray-900 text-gray-900 font-bold text-xl mb-2">
{{book_total_pay_list[current_user_moneybook.pk:2].sum()}}
</div>
</div>
</div>
</div>
</a>
{% endfor %}
Could not parse the remainder: '[current_user_moneybook.pk:2]' from 'book_total_pay_list[current_user_moneybook.pk:2]'
is there any other method or more query way?
also, I guessenter code here .sum() method is not working. is there other method to sum this price list?

Related

Django Form Post but doesn't display data

I'm working on a project but I'm kind of stuck on a problem. My Django post form doesn't have any bug but every time I submit a form, it redirects as it should but doesn't display anything. And I have 5 forms of the same type but it's only one of them that does it.
Code Snippet Below.
views.py:
########################## PRESCRIPTION #####################################################
def patients_list(request):
context = {'patients_list': Prescription.objects.all()}
return render(request, 'dashboard/patients_list.html', context)
def patients_form(request, id=0):
if request.method == 'GET':
if id == 0:
pform = PatientsForm()
else:
prescription = Prescription.objects.get(pk=id)
pform = PatientsForm(instance=prescription)
return render(request, 'dashboard/patients_form.html', {'pform': pform})
else:
if id == 0:
pform = PatientsForm(request.POST)
else:
prescription = Prescription.objects.get(pk=id)
pform = PatientsForm(request.POST, instance=prescription)
if pform.is_valid():
pform.save()
return redirect('/list')
urls.py:
########################## PRESCRIPTION #####################################################
path('form', views.patients_form, name='patients_form'),
path('list', views.patients_list, name='patients_list'),
path('update_patient/<str:id>/', views.patients_form, name="update_patient"),
path('patients_delete/<str:id>/', views.patients_delete, name="patients_delete"),
########################## END PRESCRIPTION #####################################################
patients_form.html:
<form action="" method="POST">
{% csrf_token %}
<div class="form-group">
{{pform.first_name|as_crispy_field}}
</div>
<div class="form-group">
{{pform.last_name|as_crispy_field}}
</div>
<div class="form-group">
{{pform.CNI|as_crispy_field}}
</div>
<div class="form-group">
{{pform.gender|as_crispy_field}}
</div>
<div class="form-group">
{{pform.marital_status|as_crispy_field}}
</div>
<div class="form-group">
{{pform.telephone1|as_crispy_field}}
</div>
<div class="form-group">
{{pform.telephone2|as_crispy_field}}
</div>
<div class="form-group">
{{pform.town|as_crispy_field}}
</div>
<div class="form-group">
{{pform.address|as_crispy_field}}
</div>
<div class="form-group">
{{pform.occupation|as_crispy_field}}
</div>
<div class="form-group">
{{pform.status|as_crispy_field}}
</div>
<div class="row">
<div class="col md 6">
<button class="btn btn-success my-4" type="submit"> <i class="flaticon-381-database"> </i> Submit</button>
</div>
<div class="col md 6">
<a href="{% url 'patients_list' %}" class="btn btn-secondary btn-block">Back To List
<i class="fas fa-stream"></i>
</a>
</div>
</div>
</form>
forms.py:
class PatientsForm(forms.ModelForm):
class Meta:
model = Prescription
fields = '__all__'
labels = {
'first_name': 'First Name',
'last_name': 'Last Name'
}
patients_list.html:
{% for prescription in patients_list %}
<tbody>
<tr>
<td>
<div class="custom-control custom-checkbox">
<input
type="checkbox"
class="custom-control-input"
id="customCheckBox2"
required=""
/>
<label
class="custom-control-label"
for="customCheckBox2"
></label>
</div>
</td>
<td>{{prescription.id}}</td>
<td>{{prescription.date_added}}</td>
<td>{{prescription.first_name}}</td>
<td>{{prescription.last_name}}</td>
<td>{{prescription.age}}Years</td>
<td>{{prescription.doctor}}</td>
<td>{{prescription.town}}</td>
<td>{{prescription.gender}}</td>
<td>
{% if prescription.status == 'New Patient' %}
<span class="badge badge-outline-primary">
<i class="fa fa-circle text-primary mr-1"></i>
{{prescription.status}}
</span>
{% elif prescription.status == 'In Treatement' %}
<span class="badge badge-warning light">
<i class="fa fa-circle text-warning mr-1"></i>
{{prescription.status}}
</span>
{% elif prescription.status == 'Recovered' %}
<span class="badge badge-info light">
<i class="fa fa-circle text-info mr-1"></i>
{{prescription.status}}
</span>
{% endif %}
</td>
<td>
<a href="{% url 'update_patient' prescription.id %}" class='btn text-secondary px-0'>
<i class="fa fa-pencil fa-fw"></i> Edit
</a>
</td>
<td>
<form action="{% url 'patients_delete' prescription.id %}" method='post' class='d-inline'>
{% csrf_token %}
<button class="btn text-warning px-0" type="submit"><i class="fa fa-trash-o fa-fw"></i> Delete
</button>
</form>
</td>
</tr>
</tbody>
{% endfor %}
please, try to use DGCBV in your case createView and updateView. It can be much much better. more here: https://docs.djangoproject.com/en/4.1/ref/class-based-views/flattened-index/#editing-views
in your case:
def patients_form(request, id=0):
if request.method == 'GET':
# some staff on get without return
else:
# some staffon post
if pform.is_valid():
pform.save()
return redirect('/list')
return render(request, 'dashboard/patients_form.html', {'pform': pform})
in this code you return form-render if form is NOT valid. Otherwise instance should be saved and you goes to '/list'

How get the id of a bootstrap html <a> tag id and pass it to django views.py?

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...

Field 'id' expected a number but got 'Student'

I tried to apply python manage.py migrate I get the error Field 'id' expected a number but got 'Student'.
I've set the value of primary key to be id.
views.py:
#----------------------STUDENT OPERATION------------------------------------
#login_required()
def test_form(request):
students = TestModel.objects.all()
paginator = Paginator(students,20)
page_number = request.GET.get('pages')
page_obj = paginator.get_page(page_number)
enter code here
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():
x = form.instance.student
print(x)
p = form.save(commit=False)
p.save()
messages.success(request,'Student "{}" has been succesfully added!'.format(x))
return redirect('testform')
else:
form = TestForm()
return render(request,'testform.html', {'form':form,'students':page_obj})
#login_required()
def update_form(request,id):
if request.method == 'POST': #defpost
obj = TestModel.objects.get(pk = id)
form = TestForm(request.POST,instance=obj)
if form.is_valid():
form.save()
messages.success(request,'Student "{}" was succesfully updated'.format(obj.student))
return redirect('testform')
else: #def get()
obj = TestModel.objects.get(pk=id)
print(obj.student)
print('###')
form = TestForm(instance=obj)
return render(request,'testform_update.html',{'form':form})
#login_required()
def del_testform(request,id):
if request.method == 'POST':
obj = TestModel.objects.get(pk = id)
student = obj.student
obj.delete()
messages.warning(request,'Student "{}" has been deleted succesfully!'.format(student))
return redirect('testform')
def home(request):
posts = Post.objects.all().order_by('-date_posted')[:8]
destinations = Destinations.objects.all().order_by('date_posted')[:6]
return render(request,'home.html', {'posts':posts, 'destinations':destinations})
models.py:
class TestModel(models.Model):
GENDER_CHOICES = (('Male','Male'),('Female','Female'))
student = models.CharField(max_length=100,null=True)
address = models.CharField(max_length=100)
gender = models.CharField(choices=GENDER_CHOICES,max_length=50)
email = models.EmailField(null=True)
def __str__(self):
return self.student
testform.html:
{% extends 'index.html' %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-md-8">
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }} alert-dismissible fade show my-2" role="alert">
{{ message }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endfor %}
{% endif %}
<div class="col-md-5 mr-auto">
<form method="POST">
{% csrf_token %}
<legend class="">Enter Student Details</legend>
<div class="form-group">
{{form|crispy}}
<button type="submit" class="btn btn-primary">Add Student</button>
</div>
</form>
</div>
<div>
</div>
<div class="my-2 ">
<div class="text-center border bg-white">
<h3>Student Table</h3>
</div>
<table class="table table-white table-striped table-hover table-bordered">
<tr>
<td colspan="6">
<form class="form-inline" name = "table-search" >
<div class="form-group mr-auto">
<input type="text" class="form-control" placeholder = "Search Student">
<button class="btn btn-primary ml-2 mt-1 form-control " type="submit">Search</button>
</div>
<div class="form-group">
</div>
</form>
</td>
</tr>
<thead>
<tr>
<th>SN</th>
<th>Name</th>
<th>Address</th>
<th>Gender</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
{% for student in students %}
<tr>
<td>{{forloop.counter}}.</td>
<td>{{student.student}}</td>
<td>{{ student.address}}</td>
<td>{{student.gender}}</td>
{% if student.email %}
<td>{{student.email}}</td>
{% elif student.email == None %}
<td class="text-danger">Not Available</td>
{% endif %}
<td>
<button type="button" class="btn btn-danger btn-sm" data-toggle="modal"
data-target="#staticBackdrop{{student.id}}">
<i class="fas fa-trash mr-2"></i> Delete
</button>
<a class="btn btn-primary btn-sm " href="{% url 'testform-update' student.id%}"><i class="fas fa-pen mr-2"></i> Update</a>
</td>
</tr>
<!-- modal-->
<div class="modal fade" id="staticBackdrop{{student.id}}" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel"><span class="text-danger">Delete</span></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="text-muted">Delete student <strong>"{{student.student}}"</strong>?
</div>
<div class="modal-footer">
<form method="POST" action="{% url 'testform-delete' student.id %}" name="deleteform">
{% csrf_token %}
<button class="btn btn-danger" type="submit">Delete</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close
</button>
</form>
</div>
</div>
</div>
</div>
<!-- modal-->
{% endfor %}
</table>
</div>
</div
</div>
</div>
{% endblock %}

Django HTML for loop with filter

In my django project, I have an HTML that renders questions header, and inside the question headers I have question items. In my model, Question headers and items are two different entities. I need to show for every header, just the items related to that header. As it shows all items for all questions without any filters. Greatly appreciate any help!
Model:
class Question(models.Model):
question = models.CharField(max_length=240)
mission_section = models.ForeignKey('Mission_Section', on_delete=models.CASCADE)
type_question = models.ForeignKey('Type_Question', on_delete=models.CASCADE)
categories_question = models.ForeignKey('Categories_Question', on_delete=models.CASCADE, default=1)
order = models.IntegerField(default=1)
def __str__(self):
return self.question
class Question_Option(models.Model):
question = models.ForeignKey('Question', on_delete=models.CASCADE,default=1)
option = models.CharField(max_length=240)
correct = models.BooleanField()
order = models.IntegerField(default=1)
View:
class Questions(LoginRequiredMixin, FormView):
template_name = "questions.tmpl"
def get(self, request, pk):
context = {
'pk': pk,
'section': Mission_Section.objects.get(pk = pk ),
'questions_items': Question_Option.objects.filter(question__mission_section__pk=pk).order_by('order','pk'),
'questions': Question.objects.filter(mission_section__pk = pk ),
'question_types' : Type_Question.objects.all(),
'questions_categories': Categories_Question.objects.all()}
return render(self.request, self.template_name, context)
HTML
<input type="hidden" class="form-control" id="section" name="section" value="{{section.id}}" required>
<h1>{{ section.name }}</h1>
<div id="contentDiv">
<ol>
{% for question in questions %}
<div name="question" class="form-group" id="question-{{question.id}}" >
<form class='my-ajax-form' id="form-question-{{question.id}}" method='GET' action='.' data-url='{{ request.build_absolute_uri|safe }}'>
<li><div class="input-group">
{% csrf_token %}
{{ form.as_p }}
<input type="text" value= "{{question.id}}" id="question" name="question-hidden" class="form-control">
<input type="text" value= "{{question.question}}" id="question_name_{{question.id}}" class="form-control" aria-label="Amount" onchange="UpdateQuestion({{question.id}})">
</div>
</form>
<br>
<!-- Options -->
<div id = "question_content_{{question.id}}" name="question-options" class="collapse">
<ol class="example list-group">
{% for qi in questions_items %}
<li class="list-group-item d-flex justify-content-between align-items-center" id={{qi.id}} name="opt-{{question.id}}-{{qi.id}}" onclick="setCorrect({{qi.id}},{{question.id}})" contenteditable="true">{{ qi.option }}
<span class="badge badge-warning badge-pill">-</span>
</li>
{% endfor %} </ol>
<div>
<div class="d-flex justify-content-center">Add Option</div>
<div class="d-flex justify-content-center"> <br><i class="fa fa-plus-circle fa-1x" aria-hidden="true"></i></div>
</div>
</div>
</div></li>
{% endfor %} </ol>
using this answer I figured it out Double loop in Django template
What I need is:
<div id = "question_content_{{question.id}}" name="question-options" class="collapse">
{% csrf_token %}
{{ form.as_p }}
<form class='ajax-form-option' id="form-option-{{question.id}}" method='GET' action='.' data-url='{{ request.build_absolute_uri|safe }}'>
<ol class="example list-group">
{% for qi in question.question_option_set.all %}
<li class="list-group-item d-flex justify-content-between align-items-center" id=option-{{qi.id}} name="opt-{{question.id}}-{{qi.id}}">
<div contenteditable="true">{{ qi.option }}</div>
<div>
<button type="button" name='option-check' class="btn btn-light" value={{qi.id}} id="check-option-{{question.id}}-{{qi.id}}">
<i class="fas fa-check"></i>
</button>
<button type="button" class="btn btn-warning" id="delete-option-{{question.id}}-{{qi.id}}" onclick="deleteOption({{qi.id}})">
<i class="fa fa-trash" aria-hidden="true"></i>
</button>
</div>
</li>
{% endfor %} </ol>
<div onclick="CreateOption({{question.id}})">
<div class="d-flex justify-content-center">Add Option</div>
<div class="d-flex justify-content-center"> <br><i class="fa fa-plus-circle fa-1x" aria-hidden="true"></i></div>
</div>
</form>

How to add more than item to the session in Flask

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')}} &nbspx{{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$ &nbsp&nbsp</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.

Categories

Resources