View:
class addrecipe(CreateView):
model = Recipe
template_name = 'recipebook/addrecipe.html'
fields = '__all__'
Model:
class Recipe(models.Model):
name = models.CharField(max_length=50)
description = models.CharField(max_length=200)
servings = models.IntegerField(default=1, blank=False)
tools = models.ManyToManyField(Tool)
def __str__(self):
return self.name
Template:
{% extends 'recipeBook/base.html' %}
{% block title %}Add New Recipe{% endblock title %}
{% block header %}
<header>
<a href="{% url 'recipeBook:recipe_list' %}">Recipe list</a>
</header>
{% endblock header %}
{% block content %}
<h1>Add New Recipe</h1>
<form action="" method ="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Add">
</form>
{% endblock content %}
Form:
from django import forms
from .models import Recipe, Tool
class AddRecipeForm(forms.ModelForm):
name = forms.CharField(label="Recipe Name", max_length=50)
description = forms.Textarea(max_length=200)
servings = forms.IntegerField(default=1, blank=False)
tools = forms.ModelMultipleChoiceField(queryset=Tool.objects.all(), widget=forms.CheckboxSelectMultiple, required = True)
class Meta:
model = Recipe
fields = ("__all__",)
Currently the tools field displays as follows:
I am trying to find a way to display all the tools in the database as a checklist where the user can simply check off each tool that is relevant to the recipe they are adding, or add a new tool if it's not already in the list. Is there a way to achieve this?