i Cannot access forigenkey table data in template - foreign-keys

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

Related

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)

'str' object has no attribute 'objects' django

My views.py file is
def studentFeedBack(request):
studentid = ''
courseid = ''
teacherid = ''
if request.method == 'POST':
studentid_id = request.POST.get("studentid")
studentid = studentid.objects.get(id=studentid_id)
courseid_id = request.POST.get("courseid")
courseid = courseid.objects.get(id=courseid_id)
teacherid_id = request.POST.get("teacherid")
teacherid = teacherid.objects.get(id=teacherid_id)
description = request.POST.get("description")
rating = request.POST.get("rating")
studentFeedBack.objects.create(
courseid=courseid,
description=description,
studentid=studentid,
teacherid=teacherid,
rating=rating
)
return render(
request,
'forms/studentFeedBack.html',
{
'studentids':studentid.objects.all(),
'courseids':courseid.objects.all(),
'teacherids':teacherid.objects.all(),
}
)
and my models.py file is
class StudentFeedBack(models.Model):
feedbackid = models.AutoField(primary_key=True)
courseid = models.ForeignKey('Course', on_delete=models.CASCADE)
description = models.CharField(max_length=500)
submitdate = models.DateTimeField(auto_now_add=True)
teacherid = models.ForeignKey('schoolTeacher', on_delete=models.CASCADE)
studentid = models.ForeignKey('Student', on_delete=models.CASCADE)
option = [('Good','Good'),('Average','Average'),('Bad','Bad')]
rating = models.CharField(max_length=100, choices=option, default='none')
class Course(models.Model):
courseid = models.IntegerField(primary_key=True)
coursedescription = models.CharField(max_length=500)
coursename = models.CharField(max_length=50)
userid = models.IntegerField()
code = models.CharField(max_length=50)
videolink = models.FileField(default='default_link')
createddate = models.DateTimeField()
imagelink = models.URLField(default='default_link')
duration = models.DateTimeField()
longdes = models.TextField()
coursetype = models.CharField(max_length=50)
assignto = models.CharField(max_length=200)
status = models.BinaryField()
def _str_(self):
return self.coursename
class Meta:
db_table = "courseids"
class schoolTeacher(models.Model):
teacherid = models.IntegerField(primary_key=True)
name = models.CharField(max_length=50)
address = models.CharField(max_length=200)
email = models.EmailField()
contact = models.IntegerField()
passowrd = models.CharField(max_length=13)
image = models.ImageField(default='default.jpg')
regno = models.CharField(max_length=20)
joiningdate = models.DateTimeField()
def _str_(self):
return self.name
class Meta:
db_table = "teacherids"
class Student(models.Model):
studentid = models.IntegerField(primary_key=True)
regno = models.CharField(max_length=20)
name = models.CharField(max_length=50)
email = models.EmailField(max_length=50)
contactno = models.CharField(max_length=13)
registrationdate = models.DateTimeField()
address = models.CharField(max_length=200)
password = models.CharField(max_length=13)
imagepath = models.ImageField(max_length=100, default='default.jpg')
sectionid = models.IntegerField()
def _str_(self):
return self.name
class Meta:
db_table = "studentids"
and studentFeedBack html file has the following form
<form action="/studentFeedBack/" method="POST">
{% csrf_token %}
<label for="studentid">Student Id</label>
<!-- <input type="number" name="studentid"><br><br> -->
<select name="studentid" required>
{% for studentid in studentids %}
<option value="{{studentid.id}}">{{studentid.name}}</option>
{% endfor %}
</select><br><br>
<!-- <label for="courseid">Course Id</label>
<input type="number" name="courseid"><br><br> -->
<label for="courseid">Course Id</label>
<select name="courseid" required>
{% for courseid in courseids %}
<option value="{{courseid.id}}">{{courseid.coursename}}</option>
{% endfor %}
</select><br><br>
<label for="teacherid">Teacher Id</label>
<!-- <input type="number" name="teacherid"><br><br> -->
<select name="teacherid" required>
{% for teacherid in teacherids %}
<option value="{{teacherid.id}}">{{teacherid.name}}</option>
{% endfor %}
</select><br><br>
<label for="description" >Feedback</label>
<textarea class="form-control" rows="3" name="description"></textarea><br><br>
<label for="rating">Rating</label><br>
<input type="radio" id="Good" name="rating" value="Good">
<label for="Good">Good</label><br>
<input type="radio" id="Average" name="rating" value="Average">
<label for="Average">Average</label><br>
<input type="radio" id="Bad" name="rating" value="Bad">
<label for="Bad">Bad</label><br><br>
<button type="submit" class="btn btn-primary" >Submit</button>
</form>
The studentFeedBack model has foreign keys from student, schoolTeacher and Course. This is giving error on browser that 'str' object has no attribute 'objects'
Other than that my form is not giving any values in select options and that is also probably because of this error.
The design of the view is the issue
According to the line
studentid =''
studentid remains a string . You could try proper importation of the models.
Try:
views.py
from .models import Course, Student,schoolTeacher,studentFeedBack
def studentFeedBack(request):
#studentid = ''
#courseid = ''
#teacherid = ''
if request.method == 'POST':
studentid_id = request.POST.get("studentid")
studentid = Student.objects.get(id=studentid_id)
courseid_id = request.POST.get("courseid")
courseid = Course.objects.get(id=courseid_id)
teacherid_id = request.POST.get("teacherid")
teacherid = schoolTeacher.objects.get(id=teacherid_id)
description = request.POST.get("description")
rating = request.POST.get("rating")
studentFeedBack.objects.create(
courseid=courseid,
description=description,
studentid=studentid,
teacherid=teacherid,
rating=rating
)
return render(
request,
'forms/studentFeedBack.html',
{
'studentids':Student.objects.all(),
'courseids':Course.objects.all(),
'teacherids':schoolTeacher.objects.all(),
}
)
Alternatively, Django is superb at handing forms for models
https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/#modelform
This will be better for your view as there is no validation at the moment
You could also have:
views.py
...
from django.forms.models import modelform_factory
from .models import studentFeedBack
def studentFeedBack(request):
fields=[
'courseid','description','studentid','teacherid','rating']
form=modelform_factory(studentFeedBack, fields=fields)
if request.method == 'POST':
form=modelform_factory(studentFeedBack, fields=fields, data=request.POST)
## Validates the data submitted
if form.is_valid():
## Creates a studentFeedBack instance
form.save()
## If form is invalid, it will fall through to the template with the incorrect data.
else:
### Handle the incorrect form
pass
return render(
request,
'forms/studentFeedBack.html',
{
'studentids':Student.objects.all(),
'courseids':Course.objects.all(),
'teacherids':schoolTeacher.objects.all(),
'form':form,
}
)
forms/studentFeedBack.html
<form action="/studentFeedBack/" method="POST">
{% csrf_token %}
{{form.as_p}}
</form>
https://docs.djangoproject.com/en/3.1/topics/forms/#working-with-form-templates
You may need to add a verbose_name attribute to your model fields:
models.py
class StudentFeedBack(models.Model):
...
teacherid = models.ForeignKey('schoolTeacher', on_delete=models.CASCADE, verbose_name="Teacher")
...
https://docs.djangoproject.com/en/3.1/ref/models/fields/#verbose-name
Customize as needed.
I hope this helps you understand Django better.
Edit
The function-based view has the same name as an imported model
For the first view:
from .models import Course, Student,schoolTeacher
from .models import studentFeedBack as studentFeedBackModel
def studentFeedBack(request):
#studentid = ''
#courseid = ''
#teacherid = ''
if request.method == 'POST':
studentid_id = request.POST.get("studentid")
studentid = Student.objects.get(id=studentid_id)
courseid_id = request.POST.get("courseid")
courseid = Course.objects.get(id=courseid_id)
teacherid_id = request.POST.get("teacherid")
teacherid = schoolTeacher.objects.get(id=teacherid_id)
description = request.POST.get("description")
rating = request.POST.get("rating")
studentFeedBackModel.objects.create(
courseid=courseid,
description=description,
studentid=studentid,
teacherid=teacherid,
rating=rating
)
return render(
request,
'forms/studentFeedBack.html',
{
'studentids':Student.objects.all(),
'courseids':Course.objects.all(),
'teacherids':schoolTeacher.objects.all(),
}
)

Django display value text in formset

I wanna display the text value of a foreign key on the templante, in a way that the user cannot change it.
Template:
{% for form in formset %}
<div class="">
{% for field in form %}
{{ field }}
{% endfor %}
</div>
{% endfor %}
HTML render:
<select name="form-0-semestre_solicitacao" id="id_form-0-semestre_solicitacao">
<option value="">---------</option>
<option value="5">2020/1</option>
<option value="4">2019/2</option>
<option value="3" selected="">2019/1</option>
<option value="2">2018/2</option
<option value="1">2018/1</option>
</select>
I tried {{ field.initial }} and {{ field.value }} but it displays 3 and i would like it to display the text: 2019/1
Update:
The field in display refers to the Foreign Key in semestre_solicitacao
models.py
class Solicitacao(models.Model):
"""Solicitações, depende de User e curso"""
#TODO trocar homologada de boolean para choice homologada e não homologada, e ajustar forms
solicitante = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
disciplina = models.ForeignKey(Disciplina, on_delete=models.CASCADE)
justificativa = models.TextField(("Justificativa para o pedido"),
help_text="O candidato pode explicar os motivos para solicitar a prova, por exemplo: experiência profissional, cursos não regulares, aproveitamentos indeferidos, entre outros.", blank=True, null=True)
documentos = models.FileField(("Documentos comprobatorios de conhecimentos"),
upload_to=None, max_length=100, blank=True, null=True,
validators=[FileExtensionValidator(['.pdf'])])
data_solicitacao = models.DateTimeField(
("Data da solicitação"), auto_now_add=True)
cursou_anteriormente = models.BooleanField(
("Cursou anteriormente a disciplina solicitada"), blank=True, null=True)
homologada = models.BooleanField(blank=True, null=True)
semestre_solicitacao = models.ForeignKey(Calendario, on_delete=models.CASCADE, null=True)
Views.py
from extra_views import ModelFormSetView
class ItemFormSetView(ModelFormSetView):
model = Solicitacao
fields = ['semestre_solicitacao', 'solicitante', 'disciplina', 'cursou_anteriormente']
template_name = 'manage_solicitacoes.html'
success_url = reverse_lazy('cc:solicitacoes')
factory_kwargs = {'extra': 0}
def get_queryset(self):
slug = self.kwargs['slug']
return super(ItemFormSetView, self).get_queryset().filter(semestre_solicitacao__slug=slug)
I'm using django-extra-views.
Update 2:
I'm getting the top part of the image, and i would like something similar to the one in the bottom
Others Models:
class Calendario(models.Model):
"""Calendario referente as datas do semestre"""
ano = models.CharField(
("Ano"), max_length=4,
help_text='Ano dos pedidos, ex: 2020')
semestre = models.CharField(
("Semestre"), max_length=1,
help_text='Semestre dos pedidos')
is_active = models.BooleanField('Calendário em vigor', default=True)
inicio_solicitacoes = models.DateField(
"Inicío das Solicitações", auto_now=False, auto_now_add=False)
fim_solicitacoes = models.DateField(
"Fim das Solicitações", auto_now=False, auto_now_add=False)
inicio_recursos = models.DateField(
"Inicío dos Recursos", auto_now=False, auto_now_add=False)
fim_recursos = models.DateField(
"Fim dos Recursos", auto_now=False, auto_now_add=False)
slug = models.SlugField(unique=True)
class Meta():
ordering = ['-ano', '-semestre']
constraints = [
models.UniqueConstraint(
fields=['ano', 'semestre'], name='unique_ano_semestre')
]
def __str__(self):
return f'{self.ano}/{self.semestre}'
def get_absolute_url(self):
return reverse("calendario:calendario-detail", kwargs={"slug": self.slug})
def get_delete_url(self):
return reverse("calendario:calendario-delete", kwargs={"slug": self.slug})
def save(self, *args, **kwargs):
"""Garante que exista apenas um is_active=True e define a slug"""
slug_str = f'{self.ano}-{self.semestre}'
unique_slugify(self, slug_str)
if self.is_active:
with transaction.atomic():
Calendario.objects.filter(
is_active=True).update(is_active=False)
return super(Calendario, self).save(*args, **kwargs)
else:
return super(Calendario, self).save(*args, **kwargs)
def get_fields(self):
""" Permite usar for no template para exibir todos os atributos do objeto"""
return [(field.verbose_name, field.value_to_string(self)) for field in Calendario._meta.fields]
class Curso(models.Model):
"""Cursos existente e ativos com matriz"""
nome = models.CharField(max_length=30)
abreviacao = models.CharField(
'Abreviação', max_length=3, help_text='Máximo 3 letras')
matriz = models.CharField(
max_length=4, help_text='Ano de aprovação de matriz do curso')
is_active = models.BooleanField('Ativo', default=True)
slug = models.SlugField(max_length=20)
class Meta():
ordering = ['-is_active', 'nome']
def save(self, *args, **kwargs):
slug_str = self.abreviacao + self.matriz
unique_slugify(self, slug_str)
self.abreviacao = self.abreviacao.upper()
super(Curso, self).save(*args, **kwargs)
def __str__(self):
return f'{self.abreviacao}/{self.matriz}'
def get_absolute_url(self):
return reverse("curso:curso-detail", kwargs={"slug": self.slug})
class Disciplina(models.Model):
"""Modelo disciplina"""
codigo = models.CharField(("Código"), max_length=12, primary_key=True, unique=True)
nome = models.CharField(("Nome da disciplina"), max_length=50)
curso = models.ManyToManyField('Curso')
def __str__(self):
return f'{self.codigo} - {self.nome}'
def get_absolute_url(self):
"""Url para o template com detalhes de uma disciplinas especifica"""
return reverse("curso:disciplina-detail", kwargs={"pk": self.codigo})
{{ form.instance.solicitante }} e {{ form.instance.solicitante.curso }}
Did what i wanted

I filling the fields but do not enter in form.is_valid ():

Experts I am waiting for my problem to be solved on the internet
Why when I finished filling the fields in django do not enter in form.is_valid (): Although the results are presented correctly I hope to solve this problem
class Listing(models.Model):
property_type = models.IntegerField(choices=PROPERTY_TYPE_CHOICES, default=1)
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
price = models.BigIntegerField()
roomsTotal = models.PositiveSmallIntegerField(null=True)
Bathrooms = models.PositiveSmallIntegerField(default=0)
bedrooms = models.PositiveSmallIntegerField(default=0)
Receptionrooms = models.PositiveSmallIntegerField(default=0)
livingArea = models.DecimalField(max_digits=9, decimal_places=1)
lotSize = models.DecimalField(max_digits=9, decimal_places=1)
unitType = models.IntegerField(choices=UNIT_TYPE_CHOICES, default=1)
VOnSea = models.BooleanField(default=False, blank=True)
yearBuilt = models.PositiveIntegerField(
validators=[
MinValueValidator(1900),
MaxValueValidator(datetime.datetime.now().year)],
help_text="Use the following format: <YYYY>")
hoaPrice = models.BigIntegerField(null=True,blank=True)
groundTankSize = models.DecimalField(max_digits=6, decimal_places=1,null=True,blank=True)
garageSize = models.DecimalField(max_digits=6, decimal_places=1,null=True,blank=True)
homeDescription = models.TextField(blank=True)
class ForSaleForm(forms.Form):
property_type = forms.ChoiceField(widget=forms.Select, choices=PROPERTY_TYPE_CHOICES,required=False)
price = forms.IntegerField(required=True)
roomsTotal = forms.IntegerField()
Bathrooms = forms.IntegerField(required=True)
bedrooms = forms.IntegerField(required=True)
Receptionrooms = forms.IntegerField(required=True)
livingArea = forms.DecimalField(required=True)
lotSize = forms.DecimalField(required=True)
unitType = forms.ChoiceField(widget=forms.Select, choices=UNIT_TYPE_CHOICES,required=False)
yearBuilt = forms.DateField(required=True)
def clean(self):
data = self.cleaned_data
if data.get('price', None) or (data.get('Bathrooms', None) and data.get('bedrooms', None)):
return data
else:
raise forms.ValidationError('Provide either a price and Bathrooms or a bedrooms')
form = ForSaleForm(request.POST or None)
for key in request.POST.keys():
if key != 'csrfmiddlewaretoken':
print(key,":",request.POST[key])
if form.is_valid():
propertyType = form.cleaned_data.get('propertyType')
price = form.cleaned_data.get('price')
roomsTotal = form.cleaned_data.get('roomsTotal')
Bathrooms = form.cleaned_data.get('Bathrooms')
bedrooms = form.cleaned_data.get('bedrooms')
Receptionrooms = form.cleaned_data.get('Receptionrooms')
livingArea = form.cleaned_data.get('livingArea')
lotSize = form.cleaned_data.get('lotSize')
unitType = form.cleaned_data.get('unitType')
yearBuilt = form.cleaned_data.get('yearBuilt')
listing = Listing(
user=request.user,
price=price,
roomsTotal=roomsTotal,
Bathrooms=Bathrooms,
bedrooms=bedrooms,
Receptionrooms=Receptionrooms,
livingArea=livingArea,
lotSize=lotSize,
unitType=unitType,
yearBuilt=yearBuilt,
remodelYear=remodelYear
)
listing.save()
print("saved listing")
request.POST Output: propertyType : 1 price : 443 roomsTotal : 44 Bathrooms : 5454 bedrooms : 44 Receptionrooms : 55 livingArea : 45 lotSize : 4334 unitType : 2 yearBuilt : 11 hoaPrice : groundTankSize : garageSize : homeDescription : terms : on
When you press the send button, the form refresh without showing verification messages so that it is supposed to not respond to the wrong information
<div class="md-form mb-5">
<input type='text' placeholder='حدد السعر الخاص بك' id='price' name='price' class='form-control'/>
<label for="price" class="">السعر</label>
{{ form.price.errors }}
</div>
Thanking your cooperation
add {% csrf_token %} before form.
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>

Rendering a ManyToMany Field

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 %}