Set instances of a Form without the User input - python-3.x

I am trying to set an instance of a Modelform that render through ListView.
Program Model:
class Program(models.Model):
patient = models.ForeignKey(User, on_delete=models.CASCADE, default=0)
program_name = models.CharField(max_length=1000, default="")
date_posted = models.DateTimeField(default=timezone.now)
def __str__(self):
return str(self.id) + " - " + self.patient.username + " - " + self.program_name + " - " + str(self.date_posted)
def get_absolute_url(self):
return reverse('program-detail', kwargs={'pk': self.pk})
Exercise Model:
class Exercise(models.Model):
program = models.ForeignKey(Program, on_delete=models.CASCADE, default=0)
date_posted = models.DateTimeField(default=timezone.now)
name = models.CharField(max_length=1000, default="")
description = models.TextField(default="")
load_share = models.TextField(default="")
breath_method = models.TextField(default="")
recovery_method = models.TextField(default="")
measure_method = models.TextField(default="")
notes = models.TextField(default="")
extra_info = models.TextField(default="")
reps = models.PositiveSmallIntegerField(default=0)
sets = models.PositiveSmallIntegerField(default=0)
def __str__(self):
return str(self.program_id) + " - " + str(self.pk) + " - " + " - " + self.name + " - " + str(self.date_posted)
Data Model:
exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, default="0")
set_number = models.PositiveSmallIntegerField(default=0)
spo2 = models.PositiveSmallIntegerField(default=0)
hr = models.PositiveSmallIntegerField(default=0)
physical_level = models.PositiveSmallIntegerField(default=0)
breath_level = models.PositiveSmallIntegerField(default=0)
sys = models.PositiveSmallIntegerField(default=0)
dia = models.PositiveSmallIntegerField(default=0)
misc_input = models.PositiveSmallIntegerField(default=0)
def __str__(self):
return self.exercise.name
My Exercise listView include the Data form that the User need to fill up, It is paginated to 1 exercise per page.
Exercise ListView:
# Exercise list inside each program + Data form
class ExerciseListView(LoginRequiredMixin, FormMixin, ListView):
model = Exercise
context_object_name = 'exercises'
form_class = DataForm
paginate_by = 1
def get_queryset(self):
program_num = get_object_or_404(Program, pk=self.kwargs.get('pk'))
return Exercise.objects.filter(program=program_num)
def form_valid(self, dataform):
program_num = get_object_or_404(Program, pk=self.kwargs.get('pk'))
exercises = Exercise.objects.filter(program=program_num)
for exe in exercises:
dataform.instance.exercise = exe.pk
print(dataform.instance.exercise)
return super(ExerciseListView, self).form_valid(dataform)
# Submit the Data form and redirect to the same page exercise
def add_data(request):
page = request.GET.get('page')
page = '?page={}'.format(page) if page else ''
if request.method == "POST":
form = DataForm(request.POST)
if form.is_valid():
data = form.save()
return redirect(reverse('program-detail', kwargs={'pk': data.exercise.program.pk}) + page)
forms.py:
class DataForm(forms.ModelForm):
class Meta:
model = Data
fields = ['set_number', 'spo2', 'hr']
I didn't add all the fields because it is too long for test stage.
template.py:
{% extends "program/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<h3> Program Exercises List </h3>
{% for exercise in exercises %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
{% if user.is_superuser %}
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'exercise-update' exercise.id %}">Update</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'exercise-delete' exercise.id %}">Delete</a>
<p class="article-content">{{ exercise.name }}</p>
{% else %}
<p class="article-content">{{ exercise.name }}</p>
{% endif %}
</div>
<div class="article-metadata">
<p class="article-content">{{ exercise.description }}</p>
<p class="article-content">{{ exercise.breath_method}}</p>
<p class="article-content">{{ exercise.recovery_method }}</p>
<p class="article-content">{{ exercise.measure_method }}</p>
<p class="article-content">{{ exercise.load_share }}</p>
<p class="article-content">{{ exercise.notes }}</p>
<p class="article-content">{{ exercise.extra_info }}</p>
<p class="article-content">{{ exercise.reps }}</p>
<p class="article-content">{{ exercise.sets }}</p>
</div>
<form action="{% url 'data-submit' %}{%if request.GET.page%}?page={{request.GET.page}}{%endif%}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Exercise Measurements</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Save</button>
</div>
</form>
</div>
</article>
{% endfor %}
{% if is_paginated %}
{% if page_obj.has_previous %}
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous Exercise</a>
{% endif %}
{% if page_obj.has_next %}
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next Exercise</a>
{% else %}
<a class="btn btn-outline-info mb-4" href="{% url 'web-home' %}">Exit</a>
{% endif %}
{% endif %}
{% endblock content %}
The instances I am trying to pass (in the Data form) without the user input are:
exercise - each Data form will be connect to an exercise in the database. as I mention before, the exercises are paginated 1 per page, maybe its something i can use?
I tried to solve it by that way:
def form_valid(self, dataform):
program_num = get_object_or_404(Program, pk=self.kwargs.get('pk'))
exercises = Exercise.objects.filter(program=program_num)
for exe in exercises:
dataform.instance.exercise = exe.pk
print(dataform.instance.exercise)
return super(ExerciseListView, self).form_valid(dataform)
It didn't work, I am still receiving id error for this instance.
set_number - each exercise as few sets. what I want to build is that:
the exercise as "sets" that define the number of sets the user need to perform. I want to set a "for" loop that count the number of sets and pass this instance "set_number" accordingly.
Each time the user submit the form, it will have an exercise and set_number.
Thanks!

Related

The browser or proxy sent a request that this server could not understand, 404 Bad request

I am a beginner in this field and in the process of preparing a final project for a CS50 course using Flask, Python and SQLite 3
The error appears when I try to delete the question whose position is first in the list, but the code works for the rest of the questions that are in different indexes
I don't know how to solve this bug please help!!
Thank you in advance
I have tried to print the id for each question to be deleted. Everyone is printed except for the first one print None, which gives me the error, even though it appears in the application interface.
this is my app.py code
#app.route("/list", methods=["GET", "POST"])
def list():
if request.method == "POST":
category = request.form.get("language")
if category == "All":
data = db.execute("SELECT * FROM questions")
question = []
answer = []
index = []
for item in data:
question.append(item["question"])
answer.append(item["answer"])
index.append(item["id"])
return render_template("list.html", data=zip(question,answer,index))
if request.form.get("language") == category:
data = db.execute("SELECT * FROM questions WHERE language=?", category)
question = []
answer = []
index = []
for item in data:
question.append(item["question"])
answer.append(item["answer"])
index.append(item["id"])
return render_template("list.html", data=zip(question,answer,index))
else:
data = db.execute("SELECT * FROM questions")
question = []
answer = []
index = []
for item in data:
question.append(item["question"])
answer.append(item["answer"])
index.append(item["id"])
return render_template("list.html", data=zip(question,answer,index))
#app.route("/delete", methods=["GET", "POST"])
def delete():
if request.method == "POST":
index = request.form["delete"]
print(index)
db.execute("DELETE FROM questions WHERE id=?", index)
flash("Questio deleted")
db.execute("UPDATE questions SET id = id - 1 WHERE id >?", index)
return redirect("/")
else:
data = db.execute("SELECT * FROM questions")
question = []
answer = []
index = []
for item in data:
question.append(item["question"])
answer.append(item["answer"])
index.append(item["id"])
return render_template("list.html", data=zip(question,answer,index))
and this is my list.html
{% extends "layout.html" %}
{% block title %}
list
{% endblock %}
{% block main %}
<form action="{{ url_for('list')" method="POST">
<div class="nestedGrid">
<div class="language">
<h2>Languages</h2>
<button class="list-item" name="language" value="All">ALL</button> <br>
<button class="list-item" name="language" value="python">PYTHON</button> <br>
<button class="list-item" name="language" value="c">C</button> <br>
<button class="list-item" name="language" value="javaScript">JS</button> <br>
<button class="list-item" name="language" value="java">JAVA</button> <br>
</div>
<div class="question">
<h2>Questions</h2>
<ul class="list">
{% for i, j, z in data %}
<li class="list-item panel" name=question_deleted>{{ i }}
<span class="tooltiptext">Show answer</span>
</li>
<li class="list-item panel">{{ j }}</li>
<form action="{{ url_for('delete')" method="post">
<button class="list-item" name="delete" value="{{ z }}">{{ z }} <i class="fa fa-trash"></i> </button>
</form>
{% endfor %}
</ul>
</div>
</div>
</form>
{% endblock %}
i attached screen shots of my code and my frontend app is in this repo:
screen shots
For everyone who faces the same problem, the problem was in the overlapping of requests between the list and the delete, so I combined them together in the same route using this answer:
multiple requests from the same form
and my app.py will:
#app.route("/list", methods=["GET", "POST"])
def list():
if request.method == "POST" and "language" in request.form:
cat = request.form.get("language")
if request.form['language'] == cat:
if cat == 'All':
data = db.execute("SELECT * FROM questions")
item = []
answer = []
id = []
for x in data:
item.append(x["question"])
answer.append(x["answer"])
id.append(x["id"])
return render_template("list.html", data=zip(item,answer,id))
else:
py = db.execute("SELECT * FROM questions WHERE language = ?", cat)
py_ques = []
py_answer = []
py_id = []
for i in py:
py_ques.append(i["question"])
py_answer.append(i["answer"])
py_id.append(i["id"])
return render_template("list.html", data=zip(py_ques,py_answer,py_id))
if request.method == "POST" and "deleted" in request.form:
id = request.form.get("deleted")
db.execute("DELETE FROM questions WHERE id=?", id)
flash("question deleted")
# rearange ids after deleting a question
db.execute("UPDATE questions SET id = id - 1 WHERE id > ?", id)
return redirect("/")
else :
data = db.execute("SELECT * FROM questions")
item = []
answer = []
index=[]
for x in data:
item.append(x["question"])
answer.append(x["answer"])
index.append(x["id"])
return render_template("list.html", data=zip(item,answer,index))
and list.html will:
{% extends "layout.html" %}
{% block title %}
LIST
{% endblock %}
{% block main %}
<form action = "/list" method="post">
<div class="nestedGrid">
<div class="language">
<h2>Languages</h2>
<button class="list-item" name="language" value="All">ALL</button> <br>
<button class="list-item" name="language" value="python">PYTHON <i class="fab fa-python"></i> </button> <br>
<button class="list-item" name="language" value="C">C </button><br>
<button class="list-item" name="language" value="javaScript">JS <i class="fab fa-js"></i></button><br>
<button class="list-item" name="language" value="java">JAVA <i class="fab fa-java"></i></button><br>
</div>
<div class="question">
<h2>Questions</h2>
<ul class="list">
{% for i, j, z in data %}
<li class="list-item accordion" name="question_deleted" value="{{ i }}">{{ i }}
<span class="tooltiptext">Show answer</span>
</li>
<li class="list-item panel" value="{{ j }}">{{ j }}</li>
<button class="list-item" name="deleted" value="{{ z }}"><i class="fa fa-trash" ></i></button>
{% endfor %}
</ul>
</div>
</div>
</form>
{% endblock %}
I hope this help

Django: Exception Value: The 'image' attribute has no file associated with it

Hi everyone I'm trying to create an auction system with Django.
But when I go to the item profile, Django sends me an error:
Exception Value:
The 'image' attribute has no file associated with it.
auction.html
{% extends "base.html" %}
{% block content %}
{% load static %}
<div class="page-header">
<h1>OPEN AUCTIONS</h1>
</div>
<div class="container">
<div class="row">
{% for item in auction %}
<div class="col-sm-4">
<div class="card border-secondary" style="width: 25rem;">
<div class="card-header">
Auction {{item.id}}
</div>
<img src="{{ item.image.url }}" class="card-img-top" width="250" height="180">
<div class="card-body">
<h3 class="card-title" style="text-align:center" >{{ item.object }}</h3>
<p class="card-text">{{item.description}}<br> Price: ${{ item.open_price}}<br>
End: {{ item.close_date }}</p>
<form method="POST">
{% csrf_token %}
<input type="number" name='auct_id' value={{item.id}} readonly>
<button type="submit" class="btn btn-primary btn-sm">Go</button>
</form>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
If I remove item from <img src="{{ item.image.url }}" class="card-img-top" width="250" height="180"> the page work correctly but the image doesn't display. Like this:
view.py
#login_required(login_url="login")
def auction(request):
if request.user.is_superuser:
messages.error(
request, "super user can access to admin/ and new_auction page only"
)
return redirect("new_auction")
auction = Auction.objects.filter(active=True)
for data in auction:
check = check_data(data.close_date)
if check is False:
data.active = False
data.save()
check_winner(
request, data.id
)
check_prof = check_profile(
request
)
if check_prof is True:
return redirect("profile")
auctions_open = Auction.objects.filter(active=True)
if request.method == "POST":
form = request.POST
auct_ids = form["auct_id"]
auct_id = int(auct_ids)
request.session["selected_id"] = auct_id
return redirect("betting")
else:
return render(request, "auction/auction.html", {"auction": auctions_open})
models.py
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
# Create your models here.
class Auction(models.Model):
object = models.CharField(max_length=50)
description = models.CharField(max_length=256, default="")
image = models.ImageField(upload_to="media/", null=True, blank=True)
open_date = models.DateTimeField(auto_now_add=True)
close_date = models.DateTimeField()
total_bet = models.IntegerField(default=0)
open_price = models.FloatField(
default=0,
)
close_price = models.FloatField(default=0)
winner = models.CharField(max_length=256, default="")
active = models.BooleanField(default=True)
json_details_file = models.TextField(default="")
tx = models.CharField(max_length=256, default="")
def __str__(self):
return self.object
settings.py
MEDIA_ROOT = os.path.join((BASE_DIR), "media")
MEDIA_URL = "/media/"
According to your model field image, you must give different name instead of media to upload_to.
Let's give different name to upload_to:
image = models.ImageField(upload_to="images/", null=True, blank=True) #here added images instead of media
And in your template:
instead of this:
<img src="{{ item.image.url }}" class="card-img-top" width="250" height="180">
Try this way:
<img src="/media/{{ item.image }}" class="card-img-top" width="250" height="180">
And now that images will display.
Note: don't forget to migrate after modifying upload_to="images/"

Show image name inside the image field in Django forms

I have this edit or update form in which I want to display only the image name in the form for a better user experience so that the user could know which image he has uploaded while creating the data.
I am storing the image name in the model as well,but i want to display the image name inside the image field.
forms.py
class MenuCategoryForm(forms.ModelForm):
image = forms.ImageField(allow_empty_file=True, required=False)
class Meta:
model = MenuCategory
fields = ['name', 'description', 'menu_options']
view
def menu_category_update(request, id):
item = MenuCategory.objects.get(id=id)
if request.method == 'POST':
form = MenuCategoryForm(request.POST, request.FILES, instance=item)
if form.is_valid():
if request.FILES['image']:
image = request.FILES['image']
image_url = upload_image(image, 'menu_category', image.name)
obj = form.save(commit=False)
obj.image_url = image_url
form.save()
else:
form.save()
return redirect('menu-category')
else:
form = MenuCategoryForm(instance=item)
context = {
'form': form,
'item': item
}
return render(request, 'menu/menu_category_update.html', context)
Template
{% extends 'partials/base.html' %} {% load crispy_forms_filters %} {% load
crispy_forms_tags %}
<!-- {% block title %}Menu category {% endblock %} -->
{% block content %}
<div class="container edit-form-flex">
<div class="row Edit-form-box">
<div class="form-inner-box bg-white">
<div class="heading-editing">
<h3>Edit menu category</h3>
</div>
<form method="POST" class="add-new-form edit-form" enctype="multipart/form-data">
{% csrf_token %} {{ form|crispy }}
<div class="update-buttons-container">
<button class="btn btn-info1" type="submit" value="Update">
Update
</button>
<a class="btn btn-secondary" href="{% url 'menu-category' %}"
>Cancel</a
>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
Well in other to get the name of the image in your form you will be better off in using a form initial like so:
def menu_category_update(request,id):
item = MenuCategory.objects.get(id=id)
if request.method == 'POST':
form = MenuCategoryForm(request.POST, request.FILES, instance=item)
if form.is_valid:
obj = form.save(commit=False)
# obj.username = request.user
form.save()
return redirect('menu-category')
else:
form = MenuCategoryForm(
initial={'image':item.image,
'name':item.name,
'description':iteem.description,
})# this are the fields that we want to show in the form
context = {
'form': form,
'item': item
}
return render(request, 'menu/menu_category_update.html', context)
In your form html you will apply the form initial to the field that you want to show in your form, by doing something like this: form.initial.name As i have illustrated below :
{% extends 'partials/base.html' %} {% load crispy_forms_filters %} {% load
crispy_forms_tags %}
<!-- {% block title %}Menu category {% endblock %} -->
{% block content %}
<div class="container edit-form-flex">
<div class="row Edit-form-box">
<div class="form-inner-box bg-white">
<div class="heading-editing">
<h3>Edit menu category</h3>
</div>
<form method="POST" class="add-new-form edit-form" enctype="multipart/form-data">
{% csrf_token %}
<label> Image name </label>
{{form.initial.name}}
<label> Description </label>
{{ form.initial.description }}
<label> Image </label>
{{ form.initial.image }}
<div class="update-buttons-container">
<button class="btn btn-info1" type="submit" value="Update">
Update
</button>
<a class="btn btn-secondary" href="{% url 'menu-category' %}"
>Cancel</a
>
</div>
</form>
</div>
</div>
</div>
{% endblock %}

Unable to Fetch particular product for each category

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

How to show filtered items only after adding to cart on home page in django?

i am practicing django by making an ecommerce app. I also share the video so that you can also check the problem.
https://youtu.be/crYlZ7Bo8y4
Application is working perfectly but when i filter the product according to selected category and press add to cart button then it will show all products of all categories instead of showing selected products under that category.
Can you please help me out in this.
index.html page:
{% extends 'base.html' %}
{% block content %}
{% load cart %}
{% load custom_filter %}
<!-- body -->
<div class="container-fluid mt-3">
<div class="row">
<!-- filter -->
<div class="col-lg-3 mx-auto">
<div class="list-group">
All Products
{% for category in categories %}
<a href="/?category={{category.id}}"
class="list-group-item list-group-item-action">{{category.name}}</a>
{% endfor %}
</div>
</div>
<!-- all products -->
<div id='products' class="col-lg-9 mx-auto">
<div class="row mx-auto">
{% for product in products %}
<div class="card mx-auto mb-3" id={{product.id}} style="width: 18rem;">
<img class="card-img-top" src="{{product.image.url}}" alt="Card image cap">
<div class="card-body">
<p class="card-title">{{product.name}}</p>
<p class="card-text"><b>{{product.price|currency}}</b></p>
<!-- {{product | is_in_cart:request.session.cart }} -->
</div>
<div class="card-footer p-0 no-gutters">
{% if product|is_in_cart:request.session.cart %}
<div class="row no-gutters">
<form action="/#{{product.id}}" class="col-2 " method="post">
{% csrf_token %}
<input hidden type="text" name='product' value='{{product.id}}'>
<input hidden type="text" name='remove' value='True'>
<input type="submit" value=" - " class="btn btn-block btn-light border-right">
</form>
<div class="text-center col">{{product|cart_quantity:request.session.cart}} in Cart</div>
<form action="/#{{product.id}}" class="col-2 " method="post">
{% csrf_token %}
<input hidden type="text" name='product' value='{{product.id}}'>
<input type="submit" value=" + " class="btn btn-block btn-light border-left">
</form>
</div>
{% else %}
<form action="/#{{product.id}}" method="POST" class="btn-block">
{% csrf_token %}
<input hidden type="text" name='product' value='{{product.id}}'>
<input type="submit" class="float-right btn btn-light form-control"
value="Add To Cart">
</form>
{% endif %}
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
{% endblock %}
index.py:
from django.shortcuts import render , redirect , HttpResponseRedirect
from user.models.product import Product
from user.models.category import Category
from django.views import View
# Create your views here.
class Index(View):
def post(self , request):
product = request.POST.get('product')
remove = request.POST.get('remove')
cart = request.session.get('cart')
if cart:
quantity = cart.get(product)
if quantity:
if remove:
if quantity<=1:
cart.pop(product)
else:
cart[product] = quantity-1
else:
cart[product] = quantity+1
else:
cart[product] = 1
else:
cart = {}
cart[product] = 1
request.session['cart'] = cart
print('cart', request.session['cart'])
return redirect('user:homepage')
def get(self , request):
return HttpResponseRedirect(f'/store{request.get_full_path()[1:]}')
def store(request):
cart = request.session.get('cart')
if not cart:
request.session['cart'] = {}
products = None
categories = Category.get_all_categories()
categoryID = request.GET.get('category')
if categoryID:
products = Product.get_all_products_by_categoryid(categoryID)
else:
products = Product.get_all_products();
data = {}
data['products'] = products
data['categories'] = categories
print('you are : ', request.session.get('email'))
return render(request, 'index.html', data)
urls.py:
from django.urls import path
from .views.index import Index,store
from .views.signup import Signup
from .views.login import Login,logout
app_name = 'user'
urlpatterns = [
path('', Index.as_view(), name='homepage'),
path('store', store, name='store'),
path('signup', Signup.as_view(), name='signup'),
path('login', Login.as_view(), name='login'),
path('logout', logout, name='logout'),
]
cart.py template tag:
from django import template
register = template.Library()
#register.filter(name='is_in_cart')
def is_in_cart(product , cart):
keys = cart.keys()
for id in keys:
if int(id) == product.id:
return True
return False;
#register.filter(name='cart_quantity')
def cart_quantity(product , cart):
keys = cart.keys()
for id in keys:
if int(id) == product.id:
return cart.get(id)
return 0;
#register.filter(name='price_total')
def price_total(product , cart):
return product.price * cart_quantity(product , cart)
#register.filter(name='total_cart_price')
def total_cart_price(products , cart):
sum = 0 ;
for p in products:
sum += price_total(p , cart)
return sum
Custom_filter.py template tag:
from django import template
register = template.Library()
#register.filter(name='currency')
def currency(number):
return "₹ "+str(number)
#register.filter(name='multiply')
def multiply(number , number1):
return number * number1
referer = request.META['HTTP_REFERER']
return redirect(referer)
You can get the referring page of request instead of redirecting a constant link.You can also check META

Resources