OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How can I implement few checkboxes in a Django Form?

  • Thread starter Thread starter dasEgo
  • Start date Start date
D

dasEgo

Guest
I was given a task to create a recipe website. A user can add a recipe. They have to choose a category (categories). One recipe can belong to one category or to several. I am inheriting my Form from ModelForm. Here's the code for it:

Code:
class RecipeForm(ModelForm):
    class Meta:
        model = Recipe
        fields = ['title', 'description', 'ingredients', 'cooking_steps', 'time', 'calories', 'portions', 'image', 'categories']
        widgets = {
            'title' : TextInput(attrs={'class' : 'create_recipe_title', 'placeholder' : 'Enter a title...' }),
            'description' : TextInput(attrs={'class' : 'create_recipe_description', 'placeholder' : 'Enter a short description...' }),
            'ingredients' : Textarea(attrs={'class' : 'create_recipe_ingredients', 'placeholder' : 'Your ingredients...', 'disabled' : True }),
            'time' : NumberInput(attrs={'class' : 'create_recipe_time', 'placeholder' : 'Cooking time...' }),
            'calories' : NumberInput(attrs={'class' : 'create_recipe_calories', 'placeholder' : 'Calories...' }),
            'portions' : NumberInput(attrs={'class' : 'create_recipe_portions', 'placeholder' : 'Portions...' }),
            'image' : FileInput(attrs={'class' : 'create_recipe_image'}),
            'cooking_steps' : Textarea(attrs={'class' : 'create_recipe_cooking_steps', 'placeholder' : 'Describe the cooking process...' }),
            'categories' : SelectMultiple(choices=[(1, 'Food'), (2, 'Drinks'), (3, 'Hot'), (4, 'Cold'), (5, 'Breakfast'), (6, 'Lunch'), (7, 'Dinner'), (8, 'Baked'), (9, 'Soups'), (10, 'Salads'), (11, 'Pizza and pasta'), (12, 'Sauces'),(13, 'Portugal'), (14, 'Italy'), (15, 'France'), (16, 'Japan'), (17, 'Chine'), (18, 'Georgia'), (19, 'Armenia'), (20, 'Mexico'), (21, 'Africa'), (22, 'Dietary'), (23, 'Sugar free'), (24, 'Gluten and lactose free')])
                 }

However, it doesn't work like this. It doesn't show any checkboxes at all. I am sure I am doing all the rest right. But anyway, the code for my model:

Code:
class Recipe(Model):
    title         = CharField(max_length=20)
    description   = CharField(max_length=100)
    ingredients   = CharField(max_length=200)
    cooking_steps = CharField(max_length=2000)
    time          = IntegerField()
    calories      = IntegerField()
    portions      = IntegerField()
    image         = ImageField(upload_to='static/recipes_photos')
    author        = ForeignKey(User, on_delete=CASCADE)
    rating        = IntegerField(default=0)
    categories    = ManyToManyField(Category, blank=False)
    created       = DateField(auto_now_add=True)
    last_updated  = DateField(auto_now_add=True)
    saved_by      = ManyToManyField(User, related_name='recipe_saved_by')
    left_reaction = ManyToManyField(User, related_name='recipe_left_reaction')

    recipes       = RecipeManager()
    objects       = Manager()

and my view:

Code:
class AddRecipe(View):
    template_name = 'myapp/addrecipe.html'

    def get(self, request):
        context = {'add_recipe_form' : RecipeForm(),
                   'add_ingredient_form' : IngredientForm()}
        return render(request, self.template_name, context=context)
    
    def post(self, request):
        form = ArticleForm(request.POST)
        if form.is_valid():
            recipe = form.save(commit=False)
            recipe.author = request.user
            recipe.save()        
            return redirect('recipe', recipe.pk)
        context = {'add_article_form' : form}
        return render(request, self.template_name , context=context)

Here's my template code:

Code:
         <div class='right'>
             {{ add_recipe_form.cooking_steps }}
             {{ add_recipe_form.image }}
             {{ add_recipe_form.categories }}
         </div>
     </form>

And what I see on a web: enter image description here

What am I doing wrong?
<p>I was given a task to create a recipe website. A user can add a recipe. They have to choose a category (categories). One recipe can belong to one category or to several. I am inheriting my Form from ModelForm. Here's the code for it:</p>
<pre><code>class RecipeForm(ModelForm):
class Meta:
model = Recipe
fields = ['title', 'description', 'ingredients', 'cooking_steps', 'time', 'calories', 'portions', 'image', 'categories']
widgets = {
'title' : TextInput(attrs={'class' : 'create_recipe_title', 'placeholder' : 'Enter a title...' }),
'description' : TextInput(attrs={'class' : 'create_recipe_description', 'placeholder' : 'Enter a short description...' }),
'ingredients' : Textarea(attrs={'class' : 'create_recipe_ingredients', 'placeholder' : 'Your ingredients...', 'disabled' : True }),
'time' : NumberInput(attrs={'class' : 'create_recipe_time', 'placeholder' : 'Cooking time...' }),
'calories' : NumberInput(attrs={'class' : 'create_recipe_calories', 'placeholder' : 'Calories...' }),
'portions' : NumberInput(attrs={'class' : 'create_recipe_portions', 'placeholder' : 'Portions...' }),
'image' : FileInput(attrs={'class' : 'create_recipe_image'}),
'cooking_steps' : Textarea(attrs={'class' : 'create_recipe_cooking_steps', 'placeholder' : 'Describe the cooking process...' }),
'categories' : SelectMultiple(choices=[(1, 'Food'), (2, 'Drinks'), (3, 'Hot'), (4, 'Cold'), (5, 'Breakfast'), (6, 'Lunch'), (7, 'Dinner'), (8, 'Baked'), (9, 'Soups'), (10, 'Salads'), (11, 'Pizza and pasta'), (12, 'Sauces'),(13, 'Portugal'), (14, 'Italy'), (15, 'France'), (16, 'Japan'), (17, 'Chine'), (18, 'Georgia'), (19, 'Armenia'), (20, 'Mexico'), (21, 'Africa'), (22, 'Dietary'), (23, 'Sugar free'), (24, 'Gluten and lactose free')])
}
</code></pre>
<p>However, it doesn't work like this. It doesn't show any checkboxes at all. I am sure I am doing all the rest right. But anyway, the code for my model:</p>
<pre><code>class Recipe(Model):
title = CharField(max_length=20)
description = CharField(max_length=100)
ingredients = CharField(max_length=200)
cooking_steps = CharField(max_length=2000)
time = IntegerField()
calories = IntegerField()
portions = IntegerField()
image = ImageField(upload_to='static/recipes_photos')
author = ForeignKey(User, on_delete=CASCADE)
rating = IntegerField(default=0)
categories = ManyToManyField(Category, blank=False)
created = DateField(auto_now_add=True)
last_updated = DateField(auto_now_add=True)
saved_by = ManyToManyField(User, related_name='recipe_saved_by')
left_reaction = ManyToManyField(User, related_name='recipe_left_reaction')

recipes = RecipeManager()
objects = Manager()
</code></pre>
<p>and my view:</p>
<pre><code>class AddRecipe(View):
template_name = 'myapp/addrecipe.html'

def get(self, request):
context = {'add_recipe_form' : RecipeForm(),
'add_ingredient_form' : IngredientForm()}
return render(request, self.template_name, context=context)

def post(self, request):
form = ArticleForm(request.POST)
if form.is_valid():
recipe = form.save(commit=False)
recipe.author = request.user
recipe.save()
return redirect('recipe', recipe.pk)
context = {'add_article_form' : form}
return render(request, self.template_name , context=context)
</code></pre>
<p>Here's my template code:</p>
<pre><code> <div class='right'>
{{ add_recipe_form.cooking_steps }}
{{ add_recipe_form.image }}
{{ add_recipe_form.categories }}
</div>
</form>
</code></pre>
<p>And what I see on a web:
<a href="https://i.sstatic.net/CUlk7Dbr.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/CUlk7Dbr.jpg" alt="enter image description here" /></a></p>
<p>What am I doing wrong?</p>
 

Latest posts

Online statistics

Members online
0
Guests online
3
Total visitors
3
Ads by Eonads
Top