-1

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:

enter image description here

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?

Evelyn
  • 99
  • 2
  • 10
  • It does not. I tried writing out a form but I seem to have forgotten how to render the form. Should I have placed that information in the model, instead of making a new form? I've edited the post to include the form I've written, but the page still renders the tools selection the same way as previously. – Evelyn May 18 '22 at 18:12

1 Answers1

0

I needed to add the form class to my view as follows:

class addrecipe(FormView):
    form_class = AddRecipeForm
    model = Recipe
    template_name = 'recipebook/addrecipe.html'
    fields = '__all__'
    extra_context = {
        'recipe_list': Recipe.objects.all()
    }
PTomasz
  • 1,330
  • 1
  • 7
  • 23
Evelyn
  • 99
  • 2
  • 10