In my project, there is a product.html page where the user can choose variations of the item and choose it. I don't know how to send the variant chosen by the user from a template (product.html) to admin panel.
models.py
Here is the models for OrderItem is where I want to send the value of a chosen size. Also, there is a Variation class for creating variants of the product.
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
size = models.ForeignKey(Variation, on_delete=models.CASCADE, null=True, default=Variation.title)
#property
def get_total(self):
total = self.product.price * self.quantity
return total
def __str__(self):
return self.product.name
class Variation(models.Model):
title = models.CharField(max_length=50)
category = models.CharField(max_length=120, choices=VAR_CATEGORIES, default='size')
price = models.DecimalField(null=True, blank=True, decimal_places=2, max_digits=100)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
objects = VariationManager
def __str__(self):
return self.title
product.html
Here is the page for product detail for a chosen category. My drop down with sizes is here.
{% extends "store/main.html" %}
{% block content %}
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>undefined</title>
<meta name="generator" content="Google Web Designer 14.0.4.1108">
<style type="text/css" id="gwd-text-style">
p {
margin: 0px;
}
h1 {
margin: 0px;
}
h2 {
margin: 0px;
}
h3 {
margin: 0px;
}
</style>
<style type="text/css">
html, body {
width: 100%;
height: 100%;
margin: 0px;
}
body {
background-color: transparent;
transform: perspective(1400px) matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
transform-style: preserve-3d;
}
.gwd-p-1gch {
position: absolute;
left: 170px;
top: 150px;
transform-origin: 50% 50% 0px;
width: 608px;
height: 754px;
}
.gwd-p-mo95 {
position: absolute;
width: 287.5px;
height: 159px;
left: 1069px;
top: 176px;
}
.gwd-p-uzyv {
position: absolute;
top: 363px;
width: 195px;
height: 64px;
left: 547px;
transform-style: preserve-3d;
transform: translate3d(568px, 36px, 0px) rotateZ(0.0363239deg);
}
</style>
</head>
<h3 class="htmlNoPages">
<h2>{{ product.name }}
</h2>
<p class="gwd-p-1gch">
<img data-image="black" src="{{ product.imageURL }}"
width="400"
height="500">
</p>
<p class="gwd-p-mo95">
{{ product.description }}
<div class="col-sm-4 pull-right">
<!-- Product Configuration -->
</div>
<div>
<h1 style="padding-left:920px; padding-top: 400px; font-family:sans-serif; ">
<button data-product="{{ product.id }}" data-action="add"
class="btn btn-outline-secondary add-btn update-cart">ADD TO CART
</button>
{% if product.variation_set.all %}
<select class="form-control" name="size">
{% for products in product.variation_set.all %}
<option value="{{ products }}">{{ products }}</option>
{% endfor %}
</select>
{% endif %}
</h1>
</div>
<p class="gwd-p-uzyv">
<h1 style="padding-left:920px; padding-top: 20px; font-family:sans-serif; ">£ {{ product.price }}</h1>
</p>
</h3>
</div>
</html>
{% endblock %}
Full Code:
I currently have a section in my form that looks like this:
With this form , I need to calculate Provisional Tax Date 1 and Provisional Tax Date 2 based on the Financial Year End Field ( Provisional Tax Date 1 must be 6 months after Financial Year End & Provisional Tax date 2 needs to be on the 31st of December on the year of the Financial Year End)
I would also need this to happen live, so as soon as the user changes the Financial Year End field it will update the other 2
If anyone has some sample code to assist with this, it would be highly appreciated.
Please see the below code from my project:
Views.py:
def newCompany(request):
form = CompanyForm()
if request.method == 'POST':
form = CompanyForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
print(form.errors)
content = {'form':form}
return render(request, 'main/newCompany.html', content)
Models.py
class CompanyClass(models.Model):
CompanyName = models.CharField(max_length=50 , blank=False)
RefNo = models.CharField(max_length=50 , blank=False )
FinancialYearEnd = models.DateField(auto_now=False, auto_now_add=False, null=False)
ProvisionalTaxDate1 = models.DateField(auto_now=False, auto_now_add=False)
ProvisionalTaxDate2 = models.DateField(auto_now=False, auto_now_add=False)
ARMonth = models.DateField(auto_now=False, auto_now_add=False)
checklist=models.ManyToManyField(Task)
def __str__(self):
return ( self.CompanyName)
Forms.py
class CompanyForm(ModelForm):
class Meta:
model = CompanyClass
fields = '__all__'
widgets = {
'FinancialYearEnd' : forms.SelectDateWidget,
'ProvisionalTaxDate1' : forms.SelectDateWidget,
'ProvisionalTaxDate2' : forms.SelectDateWidget,
'ARMonth' : forms.SelectDateWidget,
}
Template.html:
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
{% extends "main/base.html"%}
{% block content %}
<form class="form-group mt-4" action="" method="POST">
{% csrf_token %}
<h1 style="text-align: center "> New Company Customer </h1>
<br>
<div style="text-align: left; width: 100%; padding-left: 40px; padding-right: 60px">
<div class="row mb-3">
<div class="col">
<ul >
<li class='list-group-item ' style="background-color : #282828; color: white;">Company General Information</li>
<li class='list-group-item' style="border: 1px solid black;" style="border: 1px solid black;">Company Name {{ form.CompanyName }}</li>
<li class='list-group-item' style="border: 1px solid black;">Company Reference Number {{ form.RefNo }}</li>
<li class='list-group-item' style="border: 1px solid black;">Tax Registration Number {{ form.TaxRegNo }}</li>
<li class='list-group-item' style="border: 1px solid black;">Financial Year End {{ form.FinancialYearEnd }}</li>
<li class='list-group-item' style="border: 1px solid black;">AR Month {{ form.ARMonth }}</li>
<li class='list-group-item' style="border: 1px solid black;">Provisional Tax Date 1 {{ form.ProvisionalTaxDate1 }}</li>
<li class='list-group-item' style="border: 1px solid black;">Provisional Tax Date 2 {{ form.ProvisionalTaxDate2 }}</li>
</ul>
</div>
<div class="row mb-3">
<button type="submit" name="button" class="btn btn-primary "> Submit </button>
</div>
</div>
</form>
{% endblock %}
i am trying to develop a django webapp .i want the user to be able to submit other and get redirected to the user's platform where the user sees all his orders . i want a system where the user can make orders and get redirected to a page where will see all his orders
client form:
{% extends 'base.html' %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}
{% if user.is_authenticated %}
<div class="container" style="width: 50rem;">
<div class="col-md-10 offset-md-1 mt-5">
<div class="jumbotron">
<!--<h3 id="form-title">Job Specification </h3>-->
<h3 class="display-4" style="text-align: center;">Service Request</h3>
<p id="form-title" style="color: #343a40; text-align: center;">Please provide us with the following information</p>
<hr class="my-4">
<form action="{% url 'clients:add_item' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="col-md-4">
{{ form.job_name|as_crispy_field }}
</div>
<div class="col-md-8">
{{ form.text_description|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-md-4">
{{ form.location|as_crispy_field }}
</div>
<div class="col-md-8">
{{ form.address|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-md-6">
<!--{{ form.phone|as_crispy_field }}-->
<input style="height: 2.5rem;margin: 0 0 8px 0; width: 100%; text-align: center; position: relative; " type="text" name="phone" value="{{ user.details.phone }}" readonly><br>
</div>
<div class="col-md-6">
<input style="height: 2.5rem;margin: 0 0 8px 0; width: 100%; text-align: center; position: relative; " type="text" name="email" value="{{user.email}}" placeholder=" email " readonly><br>
</div>
</div>
<div class="row">
<div class="col-md-6">
{{ form.status|as_crispy_field }}
</div>
<div class="col-md-6" style="height: 2rem;">
<!---{{ form.customer|as_crispy_field }}-->
<input style="height: 2.5rem;margin: 0 0 8px 0; width: 100%; text-align: center; position: relative; top: 30px;" type="text" name="customer" value="{{ user.username}}" placeholder="username" readonly><br>
</div>-->
</div>
<div class="col-md-6">
<input style="height: 2.5rem;margin: 0 0 8px 0; width: 100%; text-align: center; position: relative; " type="text" name="id" value="{{ user.details.id }}" placeholder=" id " readonly><br>
</div>
<h2>
<!-- Your template -->
</h2>
<!--<div class="d-flex justify-content-center mt-3 login_container">
<input class="btn login_btn" type="submit" value="Submit">
</div>-->
<button role="button" class="btn btn-danger btn-lg">Submit</button>
</form>
</div>
</div>
</div>
{{ form.errors }}
{% else %}
<div class="container" style="width: 20rem; background-color: #6e1a52; margin-top: 70px; height: 20rem;" >
<div class="col-md-10 offset-md-1 mt-5" >
<!--<div class="jumbotron">
<h3 id="form-title" style="text-align: center;">Please login to enable you request the service you want</h3>-->
<h3 class="display-44" style="text-align: center; font-size: 22px; margin-top: 50px; color: #343a40;">request service</h3>
<p id="form-title" >Please login to enable you request the service you want</p>
<a href="{% url 'accounts:login' %}"
style="font-size: 24px; text-align: center; text-decoration: none;" >Login</a>
<!-- <a action="{% url 'profession:add_item' %}" role="button" class="btn btn-primary btn-lg">Submit</a>-->
</div>
</div>
{% endif %}
view file for client view:
#login_required
def insert_ClientJob(request):
if request.method == 'POST':
form = ClientJobForms(request.POST)
user_id=request.POST.get('id')
if form.is_valid():
product = form.save(commit=False)
#customer = ClientJob.objects.create(customer=product)
#product.customer =customer
product.save()
messages.success(request ,"successful")
return redirect('profession:user',user_id)
else:
form = ClientJobForms()
return render(request ,'job_request.html' ,{'form': form})
url file client url:
om django.urls import path
from .views import *
from .import views
app_name = 'clients'
urlpatterns = [
path('add_item/', views.insert_ClientJob ,name='add_item'),
]
model file client model:
from django.db import models
# Create your models here.
class ClientJob(models.Model):
STATUS = (
('Pending', 'Pending'),
#('On-going', 'On-going'),
('Completed', 'Completed'),
)
customer = models.ForeignKey('accounts.Customer', null=True,blank=True, on_delete= models.SET_NULL,related_name='client')
job_name = models.CharField(max_length=50,unique =False)
text_description = models.CharField(max_length=150,null=True)
location = models.ForeignKey('accounts.Area' ,on_delete =models.CASCADE)
address = models.CharField(max_length=200,unique =False)
phone =models.CharField(max_length=15,unique =False)
email = models.EmailField(unique = False)
date_created = models.DateTimeField(auto_now_add=True, null=True)
status = models.CharField(max_length=200, null=True, choices=STATUS,default='Pending')
def __str__(self):
return self.job_name
class Meta:
verbose_name_plural = "Client Job"
form file client form:
from django.db.models import fields
from django.forms import ModelForm
from django import forms
from django.contrib.auth.models import User
from .models import *
class ClientJobForms(ModelForm):
class Meta:
model = ClientJob
fields = ['job_name','text_description','location','address','phone','email','status','customer']
#fields ="__all__"
def __init__(self, *args, **kwargs):
super(ClientJobForms, self).__init__(*args, **kwargs)
self.fields['location'].empty_label ='Your location'
admin file client admin:
list_display = ('id','job_name','text_description','location','address','phone','email','date_created','status','customer')
admin.site.register(ClientJob ,ClientJobAdmin)
accounts model:
class Area(models.Model):
area_code = models.CharField(max_length=7)
location = models.CharField(max_length=100)
def __str__(self):
return self.location
class Meta:
verbose_name_plural = "Area"
class Customer(models.Model):
user = models.OneToOneField(User,null=True,blank=True, on_delete= models.SET_NULL,related_name='details')
address = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=15, null=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return str(self.user)
The error is raised :
Page not found (404) No cart matches the given query.
Request Method: GET Request
URL: http://127.0.0.1:8000/change_quan?cid=1&quantity=2
Raised by: myapp.views.change_quan
when i am trying to save quantity value in database
i tried but this error raised always
my views.py
def productcart(request):
context = {}
items = cart.objects.filter(user__id=request.user.id,status=False)
context["items"] = items
if request.user.is_authenticated:
if request.method=="POST":
pid = request.POST["pid"]
qty = request.POST["qty"]
img = request.POST["img"]
dis_price = request.POST["dis_price"]
is_exist = cart.objects.filter(product__id=pid,user__id=request.user.id,status=False)
if len(is_exist)>0:
context["msg"] = "item already exist in cart"
context["cls"] = "alert alert-warning"
else:
product = get_object_or_404(Product,id=pid)
usr = get_object_or_404(User,id=request.user.id)
c = cart(user=usr,product=product,quantity=qty,image=img,total_price=dis_price)
c.save()
context["msg"] = "{} Added in cart".format(product.name)
context["cls"] = "alert alert-success"
else:
context["status"] = "Please login first to add products to cart"
return render(request,'E-commerce-cart.html',context)
def get_cart_data(request):
items = cart.objects.filter(user__id=request.user.id,status=False)
sale,total,quantity=0,0,0
for i in items:
sale+=i.product.discount
total+=i.product.price
quantity+=i.quantity
res={
"total":total,"offer":sale,"quan":quantity
}
return JsonResponse(res)
def change_quan(request):
qty = request.GET["quantity"]
cid = request.GET["cid"]
print(request.GET)
cart_obj = get_object_or_404(cart,id=cid)
cart_obj.quantity = qty
cart_obj.save()
return HttpResponse(1)
my urls.py
"""emarket URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from os import name
from django.contrib import admin
from django.urls import path
from myapp import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.home,name='home'),
path('shop/',views.shop,name='shop'),
path('login/',views.create_user,name='login'),
path('logout/',views.user_logout,name='logout'),
path('cart/',views.productcart,name='cart'),
path('checkout/',views.checkout,name='checkout'),
path('product_detail/',views.product_detail,name='prodct-detail'),
path('find_us/',views.find_us,name='find'),
path('blog/',views.blog,name='blog'),
path('base/',views.base),
path('api/categories',views.all_categories,name="all_categories"),
path('api/brand',views.brand,name="brand"),
path('api/products',views.product_filter_api,name="product_filter_api"),
path('user_check/',views.check_user,name="check_user"),
path('filter_product/',views.filter_product,name="filter_product"),
path('add_to_favourite/',views.add_to_favourite,name="add_to_favourite"),
path('all_favourites/',views.all_favourites,name="all_favourites"),
path('forgotpass',views.forgotpass,name="forgotpass"),
path('resetpass',views.resetpass,name="resetpass"),
path('get_cart_data',views.get_cart_data,name="get_cart_data"),
path('change_quan',views.change_quan,name='change_quan'),
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
my models.py
class cart(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
product = models.ForeignKey(Product,on_delete=models.CASCADE)
image = models.ImageField(default=False)
total_price=models.FloatField(default=False)
quantity = models.IntegerField()
status = models.BooleanField(default=False)
added_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
def __str__(self):
return self.user.username
my html code
{% extends 'base.html' %}
{% block head %}
<style>
.k{height: 1px;background-color: rgb(211, 207, 207);}
.s{color:rgb(240, 240, 240);
letter-spacing: 3px;
font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
font-weight: 400;}
.cncl_icn{
float: left;
margin: 15px;
padding-top: 10px;
}
.a:hover{
background-color:rgba(152, 209, 255, 0.705);color: rgb(255, 255, 255);box-shadow:0px 0px 7px 7px rgba(204, 201, 201, 0.5) ;
}
#media screen and (max-width:680px){
.b{opacity: 0;}
/* .v{position: absolute;top: 5px;} */
.s{font-size: 15px;}
}
#media screen and (min-width:1024px){
.s{font-size: 20px;}
}
</style>
{% endblock %}
{% block body %}
{% if user.is_superuser %}
<div class="container-fluid "></div>
<h1 class="jumbotron my-5" >you are not Allowed here</h1>
{% else %}
{% if status %}
<h1 class="jumbotron my-5">{{status}}</h1>
{% else %}
{% if msg %}
<div class="{{cls}}">{{msg}}</div>
{% endif %}
<div class="row v " style="margin-right: 0%;">
<div class="col-lg-7" >
<div class="row text-center p-3 b" style="background-color: rgba(2, 184, 184, 0.863); background-attachment: fixed;">
<div class="col-md-3 "> <h3 class="s">Product</h3></div>
<div class="col-md-3 "><h3 class="s">Price</h3></div>
<div class="col-md-3 "><h3 class="s">Qantity</h3></div>
<div class="col-md-3 "><h3 class="s">Total</h3></div>
</div>
{% for i in items %}
<div class="row a border-bottom" id="col{{i.product.id}}">
<div class="col-md-3 text-center " >
<i class="far fa-times-circle cncl_icn" id="cross{{i.product.id}}" style="font-size: 30px;"></i>
<img class="mt-4" src="/media/{{i.image}}" alt="check ur internet!" height="150px">
<h4 class="ml-5" style="color: black;">{{i.product.name}}</h4>
<p class="ml-5">Size:{{i.product.size}} , color:{{i.product.color}}</p>
</div>
<div class="col-md-3 text-center mt-5">
{%if i.total_price < i.product.price%}
<del style="font-weight: bold; color: grey;" >${{i.product.price}}</del> $<p class="d-inline" style="font-weight: bold;" id="price{{i.product.id}}">{{i.total_price}}</p>
{% else %}
$<p class="d-inline" style="font-weight: bold;" id="price{{i.product.id}}">{{i.product.price}}</p>
{% endif %}
</div>
<div class="col-md-3 text-center">
<div class="form-group mt-4">
<div class="input-group">
<div class="input-group-btn ">
<button id="down" class="btn btn-default" onclick="change_quan('{{i.product.id}}','minus')" style="font-size: 25px;background: none;border: none;font-weight: bold;">-</button>
</div>
<input type="number" id="cart{{i.product.id}}" class="form-control text-center pt-3" value="{{i.quantity}}" style="width: 30px;border: none;font-weight: bold;background: none;">
<div class="input-group-btn">
<button id="up" class="btn btn-default" onclick="change_quan('{{i.product.id}}','plus')" style="font-size: 25px;background: none;border: none;font-weight: bold;">+</button>
</div>
</div>
</div>
</div>
<div class="col-md-3 mt-5 text-center">
{%if i.total_price < i.product.price %}
$<p class="d-inline" style="font-weight: bold;" id="total{{i.product.id}}">{{i.total_price}}</p>
{% else %}
$<p class="d-inline" style="font-weight: bold;" id="total{{i.product.id}}">{{i.product.price}}</p>
{% endif %}
</div>
</div>
<script>
$(function() {
$("#cross{{i.product.id}}").hover(function() {
$("#cross{{i.product.id}}").toggleClass("fas fa-times-circle").toggleClass("far fa-times-circle")
})
// to remove product from cart
$("#cross{{i.product.id}}").confirm({
title: 'Confirm',
content: 'Are you sure to remove this product from cart',
theme: 'modern',
buttons:{
confirm: function() {
$('#col{{i.product.id}}').remove()
},
cancel: function (){}
}
})
})
</script>
{% endfor %}
</div>
<script>
function grandTotal(){
$.ajax({
url:"{% url 'get_cart_data' %}",
type:'get',
success:function(data){
p = Math.round((data.offer/data.total)*100,2)
$('.item_total').html("$"+data.total)
$('#offer').html("$"+data.offer)
$('#per').html("("+p+"%)")
$('#quantity').html(data.quan)
c = (data.total)-(data.offer)
$('#grand_Total').html("$"+c)
}
})
}
grandTotal()
function change_quan(id,action){
let old = $("#cart"+id).val();
quan = 0
if(action=="plus"){
quan+=parseInt(old)+1
$('#total'+id).text( parseFloat($('#total'+id).text()) + parseFloat($('#price'+id).text()))
}
else{
quan+=parseInt(old)-1
$('#total'+id).text( parseFloat($('#total'+id).text()) - parseFloat($('#price'+id).text()))
}
$("#cart"+id).val(quan);
$.ajax({
url:"{% url 'change_quan' %}",
type:"get",
data:{cid:id,quantity:quan},
success:function(data){
alert(data)
}
});
}
</script>
<div class="col-md-5 text-center py-5" style="background-color: rgba(255, 176, 218, 0.397);">
<div id="cartt"></div>
<div class="row">
<img src="/static/Images/estore1.png" alt="" height="300px" style="margin: auto;">
</div>
<div class="pb-3 " style="font-size:30px;font-weight: bold;">--------------------</div>
<h4 class="pt-3" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">Total: <span style="font-size: 28px;" class="item_total"></span></h4>
<h4 class="pt-1" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">Quantity: <span style="font-size: 28px;" id="quantity"></span><span style="text-transform: none;"> Items</span></h4>
<h4 class="pt-1" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">You Saved: <span style="font-size: 28px;" id="offer"></span><span class='text-success'style="font-size: 20px;" id="per"></span></h4>
<h4 class="py-1" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">Grand Total: <del style="font-size: 25px; color:grey;" class="item_total"></del><span style="font-size: 28px;" id="grand_Total"></span></h4>
<h4 class="pt-3">Shipping charges will calculated at checkout</h4>
<form class="pt-3" action="" >
<!-- <input type="text" placeholder="Coupon code.." name="cod" class="mt-3 text-center" style="letter-spacing: 2px;font-size: 20px;border-radius: 25px;width: 250px;height: 47px;background-color: rgb(255, 255, 255);border:2px solid thistle;" >
<input type="submit" class="mt-3" value="Apply Code"name="acd" style="letter-spacing: 2px;font-size: 25px;border-radius: 25px;border: none;width: 250px;height: 45px;background-color: rgb(161, 158, 158);color: rgb(255, 255, 255);" > -->
<input type="submit" value="CHECKOUT" name="che" class="mt-5" style="letter-spacing: 2px;font-size: 25px;border-radius: 25px;border: none;width: 250px;height: 45px;background-color: black;color: rgb(255, 255, 255);" >
</form>
</div>
</div>
{% endif %}
</div>
{% endif %}
{% endblock %}
if data does not exist 'get_object_or_404' will throw 404 error, As per your request You are trying to retrieve data with primary key 1, but data is not available
That’s why you get this error. so please check you table or try with other pk value
def change_quan(request):
qty = request.GET["quantity"]
cid = request.GET["cid"]
print(request.GET)
cart_obj = get_object_or_404(cart,id=cid) # please check this cid value
cart_obj.quantity = qty
cart_obj.save()
return HttpResponse(1)
get_object_or_404 is not the correct choice here. Since object with id=cid was not found in database, 404 error was raised. This is the expected behaviour of get_object_or_404.
Did you mean to use get_or_create object incase the object that is trying to be fetched from database is not found?
The goal here is to show each bar corresponding to association and total members as displayed below:
What I get is this one big block with no value.
Seems that no one has the same issue here that I have been looking for.
Still a newbie so appreciate all your help & guidance, folks!
models.py
class Member(models.Model):
member_no = models.AutoField(primary_key=True)
association = models.ForeignKey('Association')
...
class Association(models.Model):
asoc_name = models.CharField(max_length=50, null=True, blank=True)
class Meta:
db_table = 'Association'
def __str__(self):
return self.asoc_name
def __unicode__(self):
return self.asoc_name
class AssociationSummary(Association):
class Meta:
proxy = True
verbose_name = 'Association Summary'
verbose_name_plural = 'Association Summary'
admin.py
#admin.register(AssociationSummary)
class ChartAssociationAdmin(admin.ModelAdmin):
change_list_template = 'admin/chart_association.html'
def changelist_view(self, request, extra_context=None):
response = super(ChartAssociationAdmin, self).changelist_view(
request,
extra_context=extra_context,
)
try:
qs = response.context_data['cl'].queryset
except (AttributeError, KeyError):
return response
metrics = {
'association': Count('asoc_name'),
'total': Sum('member'),
}
response.context_data['summary'] = list(
qs.values('asoc_name', 'member').annotate(**metrics)
)
response.context_data['summary_total'] = dict(
qs.aggregate(**metrics)
)
summary_over_time = qs.values('asoc_name', 'member').annotate(total=Sum('member'))
summary_range = summary_over_time.aggregate(
low=Min('total'),
high=Max('total'),
)
high = summary_range.get('high', 0)
low = summary_range.get('low', 0)
response.context_data['summary_over_time'] = [{
'asoc_name': x['asoc_name'],
'total': x['total'] or 0,
'pct':\
((x['total'] or 0) - low) / (high - low) * 100
if high > low else 0,
} for x in summary_over_time]
return response
chart_association.html
{% extends 'admin/change_list.html' %}
{% block content_title %}
<h1> Association Summary </h1>
{% endblock %}
{% block result_list %}
<div class=”results”>
<table>
<thead>
<tr>
<th>
<div class=”text”>
<span>Association</span>
</div>
</th>
<th>
<div class=”text”>
<span>Total Members</span>
</div>
</th>
</tr>
</thead>
<tbody>
{% for row in summary %}
<tr class="{% cycle 'row1' 'row2' %}">
<td> {{ row.asoc_name }} </td>
<td> {{ row.total }} </td>
</tr>
{% endfor %}
</tr>
<tr style="font-weight:bold; border-top:2px solid #DDDDDD;">
<td> Total </td>
<td> {{ summary_total.total }} </td>
</tr>
</tbody>
</table>
</div>
<br>
<h2> Association Chart </h2>
<style>
.bar-chart {
display: flex;
justify-content: space-around;
height: 160px;
padding-top: 60px;
overflow: hidden;
}
.bar-chart .bar {
flex: 100%;
align-self: flex-end;
margin-right: 2px;
position: relative;
background-color: #79aec8;
}
.bar-chart .bar:last-child {
margin: 0;
}
.bar-chart .bar:hover {
background-color: #417690;
}
.bar-chart .bar .bar-tooltip {
position: relative;
z-index: 999;
}
.bar-chart .bar .bar-tooltip {
position: absolute;
top: -60px;
left: 50%;
transform: translateX(-50%);
text-align: center;
font-weight: bold;
opacity: 0;
}
</style>
<div class="results">
<div class="bar-chart">
{% for x in summary_over_time %}
<div class="bar" style="height:{{x.pct}}%">
<div class="bar-tooltip">
{{ x.total | default:0 }}<br>
{{ x.asoc_name }}
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
{% block pagination %}{% endblock %}