I'm trying to display a manytomany field in my template, but all I get is a blank...I'm displaying it as below:
{% for vehicle in vehicle.features.features %}
<li>vehicle.features</li>
{% endfor %}
My model is as follows:
class Vehicle(models.Model):
stock_number = models.CharField(max_length=6, blank=False)
vin = models.CharField(max_length=17, blank=False)
common_vehicle = models.ForeignKey(CommonVehicle)
exterior_colour = models.ForeignKey(ExteriorColour)
interior_colour = models.ForeignKey(InteriorColour)
interior_type = models.ForeignKey(InteriorType)
odometer_unit = models.ForeignKey(OdometerUnit)
status = models.ForeignKey(Status)
odometer_reading = models.PositiveIntegerField()
selling_price = models.PositiveIntegerField()
purchase_date = models.DateField()
sales_description = models.CharField(max_length=60, blank=False)
feature_sets = models.ManyToManyField(FeatureSet, blank=True)
features = models.ManyToManyField(Feature, blank=True)
def __unicode__(self):
return self.stock_number
The classes I'm linking to are:
class Feature(models.Model):
name = models.CharField(max_length=32)
type = models.ForeignKey(FeatureType)
def __unicode__(self):
return self.name
class FeatureSet(models.Model):
name = models.CharField(max_length=12)
features = models.ManyToManyField(Feature)
def __unicode__(self):
return self.name
Use this:
{% for feature in vehicle.features.all %}
<li>{{ feature }}</li>
{% endfor %}
Related
views.py
def product_display_detail(request, id, *args, **kwargs):
obj21 = Product.objects.filter(id=id).values()
obj3 =Stock.objects.filter(product_id=id).values()
obj1 =Product_type.objects.all()
context = {
"object21" : obj21,
"object1" : obj1,
"object3" : obj3
}
return render(request,"product_detail.html",context)
html file
{% for s in object3 %}
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" class="custom-control-input" id="size-1" name="size">
<label class="custom-control-label" for="size-1">{{ s.size_id.size_name }}</label>
</div>
{% endfor %}
models.py
class Size(models.Model):
size_name = models.CharField(max_length=20)
class Colour(models.Model):
col_name = models.CharField(max_length=40)
class Product(models.Model):
product_name = models.CharField(max_length=120)
product_type = models.ForeignKey(Product_type, null=False, on_delete=models.PROTECT)
product_desc = models.TextField(max_length=500 , blank=False)
product_price = models.DecimalField(max_digits = 5,decimal_places = 2)
product_qty = models.IntegerField()
product_image = models.ImageField(null=False,blank=False,upload_to="images/")
def __str__(self):
return self.product_name
class Stock(models.Model):
product_id = models.ForeignKey(Product, null=True,on_delete=models.CASCADE)
size_id = models.ForeignKey(Size, null=True,on_delete=models.CASCADE)
colour_id = models.ForeignKey(Colour,null=True,on_delete=models.CASCADE)
qty = models.IntegerField()
product_details = models.TextField(max_length=500 , null=True , blank=True)
image = models.ImageField(null=False,blank=False,upload_to="images/")
i want size name from size table using stock object
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)
I am trying to do this calculation: divide a cost by a length of time (say 12 months) in order to return a monthly cost. I am able to return a value from the db but I am doing this totally wrong and I am stuck. I have also tried to use annotate instead of aggregate with no luck.
From views.py
def dashboard(request):
total_cost = Apprentice.objects.all().aggregate(Sum('cost__cost'))['cost__cost__sum']
monthly_cost = Apprentice.objects.all().aggregate(Sum('p_time__duration'))['p_time__duration__sum']
return render(request, 'dashboard.html', {'total_cost': total_cost, 'monthly_cost': monthly_cost})
From template
<div class="card">
<div class="card-body">
<h5 class="card-title">Total monthly spend</h5>
<p class="card-text"><strong></strong>£{{ monthly_cost | intcomma }}</strong></p>
</div>
</div>
From models.py
from django.db import models
from django.utils import timezone
class Division(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Department(models.Model):
name = models.CharField(max_length=255, unique=True)
division = models.ForeignKey(Division, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Programme(models.Model):
p_name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.p_name
class ProgrammeDuration(models.Model):
program = models.ForeignKey(Programme, unique=True,
on_delete=models.CASCADE)
duration = models.IntegerField()
def __str__(self):
return str(self.duration)
class Cost(models.Model):
p_name = models.ForeignKey(Programme, related_name='cost',
on_delete=models.CASCADE)
cost = models.IntegerField()
def __str__(self):
return str(self.cost)
class Apprentice(models.Model):
name = models.CharField(max_length=255)
email = models.CharField(max_length=255)
role = models.CharField(max_length=255)
p_name = models.ForeignKey(Programme, related_name='name',
on_delete=models.CASCADE)
p_time = models.ForeignKey(ProgrammeDuration, on_delete=models.CASCADE)
dept = models.ForeignKey(Department, on_delete=models.CASCADE)
div = models.ForeignKey(Division, on_delete=models.CASCADE)
cost = models.ForeignKey(Cost, on_delete=models.CASCADE)
date_created = models.DateTimeField(default=timezone.now)
on_course = models.BooleanField(null=True)
left_course = models.BooleanField(null=True)
start_date = models.DateTimeField(null=True)
finish_date = models.DateTimeField(null=True)
notes = models.TextField(null=True)
def __str__(self):
return self.name
Input from db
Rendered html
In summary, I am trying to divide the cost by the duration in months to return a monthly cost.
You have a wrong value inside monthly_cost it`s a total_duration not monthly_cost. To get monthly_cost you need to divide cost__cost__sum on p_time__duration__sum:
total_cost = Apprentice.objects.all().aggregate(Sum('cost__cost'))['cost__cost__sum']
total_duration = Apprentice.objects.all().aggregate(Sum('p_time__duration'))['p_time__duration__sum']
monthly_cost = total_cost/ total_duration
After running an index_update command I get the following message:
Indexing 452 quorum_ sensings
indexed 1 - 452 of 452 (by 4672)
This is good as there are 452 rows of data in the database. However, when I check the data fields all the data fields contain data except for the "text" field. Hence, I cannot search the database using Haystack.
What would cause the "text' field to be empty? Would, textfields in the database cause this? Any help would be much appreciated!
Here is some of my code:
search-indexes.py
from bacterial.models import Quorum_Sensing
from haystack import indexes
class Quorum_SensingIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True, template_name='quorum_sensing_text.txt')
Category_Inducer_Molecule = indexes.CharField(model_attr='Category_Inducer_Molecule', faceted=True)
Inducer_Name_Synonym_Abbreviation = indexes.CharField(model_attr='Inducer_Name_Synonym_Abbreviation', faceted=True)
Amino_Acid_Sequence_Inducer = indexes.CharField(model_attr='Amino_Acid_Sequence_Inducer', faceted=True)
Organism_Involved = indexes.CharField(model_attr='Organism_Involved', faceted=True)
Target_Protein = indexes.CharField(model_attr='Target_Protein', faceted=True)
Broad_Functional_Category_Target_Molecule = indexes.CharField(model_attr='Broad_Functional_Category_Target_Molecule',faceted=True)
def get_model(self):
return Quorum_Sensing
def index_queryset(self, using=None):
return self.get_model().objects.all()
models.py
class Quorum_Sensing(models.Model):
IUAPAC_NAME = models.CharField(max_length=400)
Inducer_Molecule = models.CharField(max_length=100)
Category_Inducer_Molecule = models.CharField(max_length=40)
Inducer_Name_Synonym_Abbreviation = models.TextField()
Chemical_Nature_Inducer_Molecule = models.CharField(max_length=40)
Natural_Synthetic = models.CharField(max_length=120)
Pubchem_Link_Inducer_Molecules = models.URLField()
Mass_Inducer_Molecule = models.CharField(max_length=50)
Number_Amino_Acids_In_Inducer_Molecule = models.CharField(max_length=60)
IUPAC_Chemical_ID = models.CharField(max_length=60)
QuorumPep_Link = models.URLField()
Amino_Acid_Sequence_Inducer = models.CharField (max_length=300)
SMILES = models.CharField(max_length=250)
Organism_Involved = models.CharField (max_length=200)
Strain1 = models.CharField(max_length=120)
Strain2 = models.CharField(max_length=120)
Strain3 = models.CharField(max_length=120)
Strain4 = models.CharField(max_length=120)
Strain5 = models.CharField(max_length=120)
Taxonomy_Link = models.URLField()
Pathogenic_Or_Not = models.CharField(max_length=120)
Host = models.CharField(max_length=120)
Target_Protein = models.CharField (max_length=160)
Target_Protein_Length = models.CharField (max_length=40)
Gene_Name = models.CharField(max_length=60)
Broad_Functional_Category_Target_Molecule = models.CharField(max_length=300)
GI = models.CharField(max_length=30)
NCBI_Link_Target_Molecule = models.URLField(max_length=400)
Mode_Of_Action = models.TextField()
UNIPROT_Link_Target_Molecule = models.URLField()
EMBL_Link_Target_Molecule = models.URLField()
Related_Citations = models.URLField(max_length=400)
Annotator = models.EmailField()
quorum_sensing_text.txt
{{ object.text }}
{{ object.Inducer_Name_Synonym_Abbreviation }}
{{ object.Category_Inducer_Molecule }}
{{ object.Amino_Acid_Sequence_Inducer }}
{{ object.Organism_Involved }}
{{ object.Target_Protein }}
{{ object.Broad_Functional_Category_Target_Molecule }}
I'm attempting to pull a user's organization, and provide a queryset to on a context processor that will get filtered through multiple different filter depending on the menu selection. The current error I am getting is as titled: Truncated incorrect DOUBLE value:(followed by the org_name of one of all the organizations databased). I have no problems until I create a news article and attach an organization.
organizations model:
class Organizations(models.Model):
org_name = models.CharField(max_length=200)
org_admin = models.ForeignKey(User) #Defines the admin user account for editing
org_description = models.CharField(max_length=1000)
org_phone = models.CharField(max_length=10)
org_county = models.ForeignKey(County)
org_address = models.CharField(max_length=200, blank=True)
org_address2 = models.CharField(max_length=200, blank=True)
org_city = models.CharField(max_length=200, blank=True)
org_zip = models.CharField(max_length=10, blank=True)
org_type = models.ForeignKey(OrgType, blank=True)
sub_org = models.ForeignKey('self', null=True, blank=True) # defines a heirarchy of organiztions
org_logo = models.ImageField(upload_to = 'pic_folder/', blank=True)
org_web = models.CharField(max_length=500, blank=True)
org_facebook = models.CharField(max_length=200, blank=True)
org_twitter = models.CharField(max_length=200, blank=True)
def __unicode__(self):
return self.org_name
news model:
class News(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(User)
slug = models.SlugField(unique=True)
content = models.TextField()
date = models.DateTimeField(default=datetime.now)
category = models.CharField(max_length=1, choices=NEWS_CATEGORIES, blank=True)
news_orgs = models.ManyToManyField(Organizations, blank=True)
news_county = models.ManyToManyField(County, blank=False)
def __unicode__(self):
return self.title
UserOrgConnections model :
class UserOrgConnections(models.Model):
user = models.ForeignKey(User)
orgs = models.ManyToManyField(Organizations)
context processor:
def mynews(request):
now = datetime.now()
if request.user.is_authenticated():
user = request.user.get_profile()
userorgs = UserOrgConnections.objects.filter(user = user)
print userorgs.values('orgs')
county = user.county.all()
MyNews = News.objects.filter(news_orgs__org_name=userorgs)
promotions = OrgPromotion.objects.filter(organization__org_county=county)
dailyspecials = OrgDailySpecials.objects.filter(organization__org_county=county)
newsall = MyNews.all().order_by('-date')
entnews = MyNews.filter(news_county=county, category='E')
technews = MyNews.filter(news_county=county, category='T')
healthnews = MyNews.filter(news_county=county, category='H')
livingnews = MyNews.filter(news_county=county, category='L')
humornews = MyNews.filter(news_county=county, category='H')
travelnews = MyNews.filter(news_county=county, category='R')
moneynews = MyNews.filter(news_county=county, category='M')
return {
'newsall': newsall,
'now': now,
'entnews': entnews,
'technews': technews,
'livingnews': livingnews,
'humornews': humornews,
'travelnews': travelnews,
'moneynews': moneynews,
}
The template snippet:
{% for newsall in newsall %}
{% if newsall.date >= now %}
{{ newsall }}
{{newsall.date }}
{% endif %}
{% endfor %}
The following sequence of code looks suspicious:
userorgs = UserOrgConnections.objects.filter(user = user)
MyNews = News.objects.filter(news_orgs__org_name=userorgs)
This is effectively asking for a sequence of News objects whose news_orgs.org_name value is equal to the list of userorgs. You haven't listed the model for UserOrgConnections so it's not possible to determine a solution with the information provided.
Perhaps you should look at the Django Queryset in operator which is capable of performing a query which filters on a list.