django - mysql selecting data from db does not work well - django

In main.html:
{% for item in count_list %}
{{ item }}<br>
{% endfor %}
In views.py:
def four(request):
count_list = PDivContent.objects.filter(divv = '5')
return render(request, 'main.html', {'count_list': count_list})
The problem is that the count_list list, contains data repeated for twice like this:
طلا و جواهرات
بدلیجات و نقره سرا
اجناس کادویی
اسباب بازی فروشی
صنایع دستی
فروش و تعمیر ساعت
طلا و جواهرات
بدلیجات و نقره سرا
صنایع دستی
اجناس کادویی
اسباب بازی فروشی
How can I solve it?
models.py:
class PDivContent(models.Model):
chest = models.IntegerField()
divv = models.IntegerField()
txt = models.TextField()
img = models.TextField()
symbol = models.TextField()
def __str__(self):
return self.txt
class Meta:
managed = False
db_table = 'p_div_content'
And in the db, data are not repeated for twice.

How about trying .distinct() in your query?
def four(request):
count_list = PDivContent.objects.filter(divv = '5').distinct()
return render(request, 'main.html', {'count_list': count_list})

Related

Add products with different sizes and price to Cart | Django

I use session's to create a shopping cart. I have a product model and a model for Product-sizes, which I define the size-title(XL , etc) and price of product in it . So that I can have products with different sizes as well as different prices. But my logic has some problems
if I add product_1 with size A , it's ok ...
if I add product_1 with size B , it's ok ...
but when I'm trying to add same product with different sizes at same time the cart only shows the price of first size
#shop/models.py
class ProductSizes(models.Model):
name = models.CharField(max_length=50)
price = models.IntegerField()
picture = models.ImageField(upload_to="products/%Y/%m/%d" )
class Product(models.Model):
name = models.CharField(max_length=100)
size = models.ManyToManyField(ProductSizes , blank=True , related_name="sizes" )
price = models.IntegerField()
#cart/cart.py
from django.conf import settings
from shop.models import Product
class Cart:
def __init__(self,request):
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
# add to cart
def add(self,product,size_,quantity=1,override_quantity=False):
product_id = str(product.id)
print(product.size.name)
if product_id not in self.cart :
if size_ != None:
if size_.off_price:
self.cart[product_id] = {'quantity':0,'price':size_.off_price}
elif size_.price:
self.cart[product_id] = {'quantity':0,'price':size_.price}
else:
if product.off_price:
self.cart[product_id] = {'quantity':0,'price':product.off_price}
else:
self.cart[product_id] = {'quantity':0,'price':product.price}
if override_quantity:
self.cart[product_id]['quantity'] = quantity
else:
self.cart[product_id]['quantity'] += quantity
self.save()
def save(self):
self.session.modified = True
#remove from cart
def remove(self,product):
product_id = str(product.id)
if product_id in self.cart:
del self.cart[product_id]
self.save()
def __iter__(self):
product_ids = self.cart.keys()
products = Product.objects.filter(id__in=product_ids)
cart = self.cart.copy()
for product in products:
cart[str(product.id)]['product'] = product
for item in cart.values():
item['total_price'] = item['price'] * item['quantity']
yield item
def __len__(self):
return sum(item['quantity'] for item in self.cart.values())
def get_total_price(self):
return sum(item['price'] * item['quantity'] for item in self.cart.values())
def clear(self):
del self.session[settings.CART_SESSION_ID]
self.save()
ــــــــــــــــــ
from django.shortcuts import get_object_or_404 , redirect , render
from django.views.decorators.http import require_POST
from .cart import Cart
from shop.models import Product, ProductSizes
from .forms import CartAddProductForm
#require_POST
def cart_add(request , product_id , size):
cart = Cart(request)
product = Product.objects.get(id=product_id)
if size != 0:
size_ = product.size.get(id=size)
else:
size_ = None
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product , quantity=cd['quantity'] ,size_=size_, override_quantity=cd['override'] )
return redirect("home")
#require_POST
def cart_remove(request , product_id):
cart = Cart(request)
product = get_object_or_404(Product,id=product_id)
cart.remove(product=product)
return redirect("cart.detail")
def cart_detail(request):
cart = Cart(request)
for item in cart:
item['update_quantity_form'] = CartAddProductForm(initial={
'quantity':item["quantity"],
"override":True,
})
return render(request , "cart.html" , {"cart":cart})
#cart/forms.py & urls
from django import forms
PRODUCT_QUANTITY_CHOICES = [(i , str(i)) for i in range(1,21)]
class CartAddProductForm(forms.Form):
quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES,coerce=int)
override = forms.BooleanField(required=False, initial=False,widget=forms.HiddenInput)
---------------
urlpatterns = [
path("" , views.cart_detail , name="cart.detail"),
path("add/<int:product_id>/<int:size>/" , views.cart_add , name="cart.add"),
path("remove/<int:product_id>/" , views.cart_remove , name="cart.remove"),
]
#html
<div class="shopping-cart-wrap">
<span class="cart-total-amunt">{{cart.get_total_price}} تومان</span><i class="icon-shopping-bag2 float-left"></i><span class="cart-total">{{cart|length}}</span>
<ul class="mini-cart">
{% for item in cart %}
<li class="cart-item">
<div class="cart-image">
<img alt="" src="/media/{{item.product.picture}}" width="80" height="80">
</div>
<div class="cart-title">
<a href="single-product.html">
<h4>{{item.product.name}}</h4>
</a>
<div class="quanti-price-wrap">
<span class="quantity">{{item.quantity}} ×</span>
<div class="price-box"><span class="new-price">{{item.price}} تومان</span></div>
</div>
<a class="{% url 'cart.remove' item.product.id %}" href="#"><i class="icon-x"></i></a>
</div>
</li>
{% endfor %}
<li class="subtotal-box">
<div class="subtotal-title">
<h3>جمع کل :</h3><span>{{cart.get_total_price}} تومان</span>
</div>
</li>
<li class="mini-cart-btns">
<div class="cart-btns">
مشاهده سبد
پرداخت
</div>
</li>
</ul>
</div>
after 2 days of struggling finally I found the solution
for adding products with different sizes you have to pass the size model id to session instead of the product id
shop/models.py
class ProductSizes(models.Model):
name = models.CharField(max_length=50)
price = models.IntegerField()
off_price = models.IntegerField(blank=True , null=True)
picture = models.ImageField(upload_to="products/%Y/%m/%d" )
product = models.ForeignKey("Product" , on_delete=models.CASCADE )
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True)
picture = models.ImageField(upload_to="products/%Y/%m/%d" )
picture2 = models.ImageField(upload_to="products/%Y/%m/%d" , blank=True)
picture3 = models.ImageField(upload_to="products/%Y/%m/%d" , blank=True)
picture4 = models.ImageField(upload_to="products/%Y/%m/%d" , blank=True)
price = models.IntegerField()
available = models.BooleanField(default=True)
category = models.ForeignKey(Category ,on_delete=models.CASCADE , blank=True ,null=True )
slug = models.SlugField(max_length=100 , db_index=True , unique=True)
tags = TaggableManager(blank=True)
is_amazing = models.BooleanField(default=False)
amazing_till = models.CharField(max_length=10 , null=True , blank=True)
off_price = models.IntegerField(blank=True , null=True)
brand = models.ForeignKey(Brand ,on_delete=models.CASCADE , blank=True ,null=True )
created_at = models.DateField(auto_now_add=True)
update_at = models.DateField(auto_now=True)
def get_absolute_url(self):
return reverse('get.single.product', kwargs={'slug': self.slug})
class Meta:
ordering=("name",)
index_together = (('id' , 'slug'),)
cart/cart.py
from django.conf import settings
from shop.models import Product, ProductSizes
class Cart:
def __init__(self,request):
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
# add to cart
def add(self,product,size_,quantity=1,override_quantity=False):
size_id = str(size_.id)
if size_id not in self.cart:
if size_.price:
self.cart[size_id] = {'quantity': 0, 'price': size_.price}
elif size_.off_price:
self.cart[size_id] = {'quantity': 0, 'price': size_.off_price}
self.cart[size_id]['quantity'] += quantity
self.save()
self.save()
def save(self):
self.session.modified = True
#remove from cart
def remove(self,size_):
product_id = str(size_.id)
if product_id in self.cart:
del self.cart[product_id]
self.save()
def __iter__(self):
sizes_ids = self.cart.keys()
products = ProductSizes.objects.filter(id__in=sizes_ids)
cart = self.cart.copy()
for size in products:
cart[str(size.id)]['size'] = size
for item in cart.values():
item['total_price'] = item['price'] * item['quantity']
yield item
def __len__(self):
return sum(item['quantity'] for item in self.cart.values())
def get_total_price(self):
return sum(item['price'] * item['quantity'] for item in self.cart.values())
def clear(self):
del self.session[settings.CART_SESSION_ID]
self.save()
cart/views.py
#require_POST
def cart_add(request , product_id , size):
cart = Cart(request)
product = Product.objects.get(id=product_id)
size_ = get_object_or_404(ProductSizes , id=size)
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product , quantity=cd['quantity'] ,size_=size_, override_quantity=cd['override'] )
return redirect("home")
The template
{% block cart %}
<div class="shopping-cart-wrap">
<span class="cart-total-amunt">{{cart.get_total_price}} تومان</span><i class="icon-shopping-bag2 float-left"></i><span class="cart-total">{{cart|length}}</span>
<ul class="mini-cart">
{% for item in cart %}
<li class="cart-item">
<div class="cart-image">
<img alt="" src="/media/{{item.size.product.picture}}" width="80" height="80">
</div>
<div class="cart-title">
<a href="single-product.html">
<h4>{{item.size.name}}</h4>
</a>
<div class="quanti-price-wrap">
<span class="quantity">{{item.quantity}} ×</span>
<div class="price-box"><span class="new-price">{{item.price}} تومان</span></div>
</div>
<a class="{% url 'cart.remove' item.size.id %}" href="#"><i class="icon-x"></i></a>
</div>
</li>
{% endfor %}
<li class="subtotal-box">
<div class="subtotal-title">
<h3>جمع کل :</h3><span>{{cart.get_total_price}} تومان</span>
</div>
</li>
<li class="mini-cart-btns">
<div class="cart-btns">
مشاهده سبد
پرداخت
</div>
</li>
</ul>
</div>
{% endblock cart %}

how to access the id of a ManyToManyField object?

my models:
class Aula(models.Model):
nome_aula = models.CharField(max_length=255)
descricao_aula = models.TextField()
...
def __str__(self):
return self.nome_aula
class Modulos(models.Model):
numero_modulo = models.CharField(default="Módulo 1",max_length=400)
aulas = models.ManyToManyField(Aula)
def __str__(self):
return self.numero_modulo
my views:
def aulasdomodulo(request, id):
mod = get_object_or_404(Modulos, pk=id)
aulas = mod.aulas.all()
return render(request, 'wtic/aulasdomodulo.html', {'aulas':aulas, 'mod':mod})
def conteudodaaula(request, id):
mod2 = get_object_or_404(Modulos, pk=id)
aula = mod2.aulas.all()
...
return render(request,'wtic/conteudo_aula.html', {'aula':aula})
my html where it shows the objects assigned that module accesses them
{% for aula in aulas %}
{{aula.nome_aula}}
Acessar
{% endfor %}
but when I try to access classes I get it
how can i access these objects one per page?

filter category Django

I want to make a button to filter product by category.. Example Salad or Meat. Without Model ProductAtribuut im able to do it, but now i added the model, so im real confused how i can get the data of a Foreign Key inside a Foreign Key
ProductAtribuut -> Product(FK) -> Categorie(FK)
Models.py
class Categorie(models.Model):
naam = models.CharField(max_length=150,db_index=True)
slug = models.SlugField(unique=True)
class MPTTMeta:
order_insertion_by = ['naam']
class Meta:
ordering=('-naam',)
def __str__(self):
return self.naam
def get_absolute_url(self):
return reverse('JavaKitchen:product_by_categorie', args=[self.slug])
#property
def get_products(self):
return Product.objects.filter(categorie__naam=self.naam)
class Groente(models.Model):
groente = models.CharField(max_length=100)
def __str__(self):
return self.groente
class Vlees(models.Model):
vlees = models.CharField(max_length=100)
def __str__(self):
return self.vlees
class Product(models.Model):
slug = models.SlugField(unique=True, primary_key=True)
titel = models.CharField(max_length=200)
beschrijving = models.TextField(blank=True, null=True)
categorie = models.ForeignKey(Categorie, on_delete=models.CASCADE)
class Meta:
ordering=('-titel',)
def __str__(self):
return self.titel
def get_title_uppercase(self):
return self.titel.upper()
def get_absolute_url(self):
return reverse('JavaKitchen:product_detail',args=[self.id,])
class ProductAtribuut(models.Model):
def groente():
return Groente.objects.filter(groente='geen').first()
def vlees():
return Vlees.objects.filter(vlees='geen').first()
product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=False)
groente = models.ForeignKey(Groente, on_delete=models.CASCADE, default=groente)
vlees = models.ForeignKey(Vlees, on_delete=models.CASCADE, default=vlees)
prijs = models.FloatField(default=0)
afbeelding = models.ImageField(blank=True, upload_to='gerechten/') #later upgrade..
zichtbaar = models.BooleanField(default=True)
def __str__(self):
return self.product.titel
def image_tag(self):
return mark_safe('<img src="/media/%s" width="80" height="auto" />' % (self.afbeelding))
image_tag.short_description = 'Image'
Views.py
def product_list(request,categorie_slug=None):
categorie = None
javakitchen = JavaKitchen.objects.get(id=1)
openings_tijden = Openings_tijden.objects.all()
categories = Categorie.objects.all().filter(zichtbaar=True)
product = Product.objects.all()
productatribuut = ProductAtribuut.objects.all().filter(zichtbaar=True)
if categorie_slug:
categorie = get_object_or_404(Categorie,slug=categorie_slug)
product = productatribuut.filter(product=product)
context = { 'categories':categories,
'categorie':categorie,
'product':product,
'form':form,
'javakitchen':javakitchen,
'openings_tijden': openings_tijden,
'productatribuut': productatribuut
}
return render(request, 'pages/index.html', context)
HTML template
<div class="categories">
<h1>{% if categorie %}{{ categorie.naam }}{% else %} ALLE GERECHTEN {% endif %}</h1>
<ol class="type">
<li><a class="page-scroll" href='{% url "JavaKitchen:product_list" %}#dinner'>Alles</a></li>
{% for c in categories %}
<li><a class="page-scroll" href="{{ c.get_absolute_url }}#dinner">{{ c.naam }}</a></li>
{% endfor %}
</ol>
<div class="clearfix"></div>
</div>
I used this before to get the category. when i didnt have class ProductAtribuut
if categorie_slug:
categorie = get_object_or_404(Categorie,slug=categorie_slug)
product = product.filter(categorie=categorie)
but now i dont know how i do get the category
ProductAtribuut -> Product(fk) -> Categorie(fk)

unable to save model form data in database. gives patientmedinfo.errors = none and patientmedinfo.is_valid() = false

'I am new to Django, trying to save my form data in the database.created two model classes PatientInfo and patientHist, which is inheriting PatientInfo class. I do not understand where I am going wrong.
'.I am not getting any error,my tables are created in database, but no data is saving when i click on submit button'
models.py
from django.db import models
# Create your models here.
class PatientInfo(models.Model):
sex = (
('M', 'Male'),
('F', 'Female')
)
first_name = models.CharField(max_length=35)
middle_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField(max_length= 30)
sex = models.CharField(max_length=1,choices=sex)
date_of_birth = models.DateField()
height = models.FloatField()
weight = models.FloatField()
phone_no =models.CharField(max_length=15)
class PatientHist(PatientInfo):
Yes_No = (
(True, 'Yes'),
(False, 'No'),
)
Veg_nonveg =(
(True,'Veg'),
(False,'Non-Veg'),
)
diabetes = models.BooleanField(default=False,choices=Yes_No)
diabetes_long = models.CharField(max_length=20)
hypertension = models.BooleanField(default=False,choices=Yes_No)
hypertension_long = models.CharField(max_length=20)
obesity = models.BooleanField(default=False,choices=Yes_No)
obesity_long = models.CharField(max_length=20)
pcod = models.BooleanField(default=False,choices=Yes_No)
pcod_long= models.CharField(max_length=20)
thyroid = models.BooleanField(default=False,choices=Yes_No)
thyroid_long = models.CharField(max_length=20)
heartdiease = models.BooleanField(default=False,choices=Yes_No)
heartdiease_long = models.CharField(max_length=20)
liverdisease = models.BooleanField(default=False,choices=Yes_No)
liverdisease_long = models.CharField(max_length=20)
kidney = models.BooleanField(default=False,choices=Yes_No)
kidney_long = models.CharField(max_length=20)
familyhistory = models.BooleanField(default=False,choices=Yes_No)
currentmed = models.CharField(max_length=20)
foodhabit= models.BooleanField(default=False,choices= Veg_nonveg)
hba1c = models.FloatField(max_length=20)
fasting = models.FloatField(max_length=20)
pp = models.FloatField(max_length=20)
forms.py
from django import forms from .models import *
class Patient_form(forms.ModelForm):
class Meta:
model = PatientInfo
fields = "__all__"
class PatientHistory_form(forms.ModelForm):
class Meta:
model = PatientHist
widgets = {
'diabetes': forms.RadioSelect,
'hypertension': forms.RadioSelect,
'obesity': forms.RadioSelect,
'pcod': forms.RadioSelect,
'thyroid': forms.RadioSelect,
'heartdiease': forms.RadioSelect,
'liverdisease': forms.RadioSelect,
'kidney':forms.RadioSelect,
'familyhistory' : forms.RadioSelect,
'currentmed':forms.RadioSelect,
'foodhabit':forms.RadioSelect,
}
fields = "__all__"
views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .forms import Patient_form,PatientHistory_form
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic
# Create your views here.
#def home(request):
#return render(request,'home/base.html',{})
#def patient_view(request):
#context = {}
# context['form'] = Patient()
#return render(request, 'home/Patient_info.html', context)
#def patienthistory_view(request):
# context = {}
# context['history'] = PatientHistory_form
# return render(request, 'home/Patient_info.html', context)
def patienthistory_view(request):
if request.method == 'POST':
patientmedinfo = PatientHistory_form(request.POST)
if patientmedinfo.is_valid():
myid = patientmedinfo.save()
myid.save()
return HttpResponse( print(patientmedinfo.errors))
else:
patientmedinfo = PatientHistory_form()
return render(request, 'home/Patient_info.html', {'form': patientmedinfo})
patient_Info.html
{% extends "home/base.html" %}
{% block title %}Patient Information{% endblock title %}
{% block content %}
<form enctype="multipart/form-data" action=" " method="post" >
{% csrf_token %} <table align="center" border="0">
<tr>
<td><h4 align="center">Patient Information</h4></td>
<td>{{form}}</td>
<td><input align="center" type="submit" value=" Next--> "></td>
</tr> </table> </form>
{% endblock content %}
Hi finally I found your error.
you have a field currentmed which is CharField.
But in forms.py you assigned forms.RadioSelect widget to it. So it throws an error for required field.
So just remove 'currentmed':forms.RadioSelect, from widget dict of PatientHistory_form.
That's it.

django form processing and submit issues

New to Django.I retrieve data from mysql db that are displayed into a form.User needs to choose among the form choices. The view processes data that have been posted from the form by querying the DB and should send the results in csv format or in graph.I am trying right now to create a csv file with the results of the query but submit does not work.
views.py:
def monitor(request):
if request.method == 'POST' :
forms = ServicesForm(request.POST)
if forms.is_valid():
service = forms.cleaned_data['service']
scale = forms.cleaned_data['scale']
datatype = forms.cleaned_data['datatype']
starttime = forms.cleaned_data['starttime']
endtime = forms.cleaned_data['endtime']
id = Servicenames.objects.raw('SELECT id FROM servicenames WHERE servicename = ' + service )
# process and create query Select "dtime",datatype where "scale" = scale and "dtime' between starttime and endtime
# and service_id
servicestats = Servicestats.objects.raw('SELECT distinct dtime,'+ datatype + ' FROM servicestats WHERE scale = '+ scale + ' AND dtime between '+ starttime + ' and '+ endtime + 'and service_id = '+ id.id)
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment;filename="export.csv"'
writer = csv.writer(response)
for s in servicestats:
writer.writerow([s.dtime,s.datatype])
return response
else:
forms = ServicesForm
return render_to_response('monitor/monitor.html', {'forms':forms},
context_instance = RequestContext(request))
models.py :
class Servicenames(models.Model):
id = models.IntegerField(primary_key=True)
servicename = models.CharField(unique=True, max_length=255)
class Meta:
db_table = u'servicenames'
def __unicode__(self):
return self.servicename
class Servicestats(models.Model):
# service_id = models.IntegerField(primary_key=True)
service_id = models.ForeignKey(Servicenames)
dtime = models.DateTimeField(primary_key=True)
scale = models.IntegerField(primary_key=True)
cnt = models.IntegerField()
min = models.FloatField()
max = models.FloatField()
avg = models.FloatField()
threenines = models.FloatField()
class Meta:
db_table = u'servicestats'
forms.py :
class ServicesForm(forms.Form):
services=Servicenames.objects.all()
service = forms.ModelMultipleChoiceField(queryset=services,widget=forms.Select(attrs={'class':'colr',}))
scales = Servicestats.objects.values_list('scale', flat=True).distinct()
scale = forms.ModelChoiceField(queryset=scales,widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))
DATATYPE_CHOICES = (
('cnt', 'cnt'),
('min', 'min'),
('max', 'max'),
('avg', 'avg'),
('threenines','threenines'),
)
datatype = forms.ChoiceField(choices = DATATYPE_CHOICES,widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))
starttime = forms.DateTimeField(initial = datetime.now)
endtime = forms.DateTimeField(initial = datetime.now)
template.html :
% extends "bbase.html" %}
{% block extrascripts %}
$("#monitor").addClass("active")
{% endblock %}
{% block content %}
<div class="main">
<p>Welcome to the monitoring management system.</p>
<p>Stay tuned for more details</p>
</div>
<div>{{forms.service}}<span id="selection"><--Select services</span></div>
<div>{{forms.scale}}<span id="selection"><--Select resolution</span></div>
<div>{{forms.datatype}}<span id="selection"><--Select data type</span></div>
<div>{{forms.starttime}}<span id="selection"><--Select start time</span></div>
<div>{{forms.endtime}}<span id="selection"><--Select end time</span></div>
<input type = "submit" value = "Submit">
{% endblock %}
Thanks for the help.
It seems you are missing a form tag around your form!
try
<form action='' method='post'>{% csrf_token %}
...your form html...
...inputs...
...submit...
</form>