1👍
For an recipe object, say r
:
r.ingredients_set.all()
will list all the ingredients linked to that recipe.
You can further filter on this:
r.ingredients_set.filter(title__startswith='clover')
There’s a comprehensive guide in Django Documentation:
https://docs.djangoproject.com/en/1.9/topics/db/examples/many_to_one/
Suppose you want the list of all ingredients for a recipe in your views.py:
ingredient_list = r.ingredients_set.all()
Then pass the ingredient_list in your context dictionary to your template. If you don’t know what context dictionary is, what are you doing man, go through the Django documentation! Lot’s of people put in lot of effort to create that nice documentation.
suppose context['ingredients'] = ingredient_list
, where context
is the context dictionary you are passing to your template html.
Then in your template, use Django Template Language for something like this:
{% for i in ingredients %}
<p>{{ i.ingredient }}</p>
{% endfor %}
Here ingredients
is the ingredient_list
you passed using the context dictionary, and for each ingredient object i
in the for loop, you are displaying the value of <ingredient object i>.ingredient
Here’s a link to the official tutorial, if it helps.
https://docs.djangoproject.com/en/1.9/intro/tutorial01/
0👍
See here: https://docs.djangoproject.com/en/1.9/topics/class-based-views/generic-display/#adding-extra-context
class PublisherDetail(DetailView):
model = Publisher
class RecipeView(generic.DetailView):
model = recipe
template_name = 'whatsfordinner/recipe.html'
context_object_name = 'details'
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(RecipeView, self).get_context_data(**kwargs)
# Add in a QuerySet of all the books
context['ingredient_list'] = recipe.ingredients_set.all()
return context
above is untested
- One login form for two types of accounts and LoginRequiredMixin in django
- Reverse for view fails because argument is None
- Super() method resolution in python