Checkboxes and Radio buttons in Django ModelForm

10,240

Solution 1

you can do something like this

CHOICES=[('item1','item 1'),
         ('item2','item 2')]
class OrderCreateForm(forms.ModelForm):
    postal_code = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())
    ....
class Meta:
    model = Order
    fields = ['first_name', 'last_name', 'email', 'address', 'postal_code', 'city']

similarly, you can do for the other field also

and for checkbox, you can define it as a BooleanFileld and you can use

{{ form.paid }}

in you template.

Solution 2

The form will be rendered with the field types you define in the model:

  • BooleanField is rendered as a checkbox, paid in your case.
  • ChoiceField can be rendered as radio buttons with the appropiate widget.

You can redefine the widgets in class OrderCreateForm:

CHOICES = [('option1','label 1'), ('option2','label 2')] some_field = forms.ChoiceField(choices=CHOICES,widget=forms.RadioSelect())

Share:
10,240
Kuba
Author by

Kuba

Updated on June 06, 2022

Comments

  • Kuba
    Kuba almost 2 years

    Welcome friends,

    I'm a newbie in Django. I need your help. Seriously.

    I want to add checkboxes and radio button in my form.

    Any help will be appreciated.

    models.py

    from django.db import models
    from shop.models import Product
    
    class Order(models.Model):
        first_name = models.CharField(max_length=50)
        last_name = models.CharField(max_length=50)
        email = models.EmailField()
        address = models.CharField(max_length=250)
        postal_code = models.CharField(max_length=20)
        city = models.CharField(max_length=100)
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)
        paid = models.BooleanField(default=False)
    
        class Meta:
            ordering = ('-created',)
    
        def __str__(self):
            return 'Order {}'.format(self.id)
    
        def get_total_cost(self):
            return sum(item.get_cost() for item in self.items.all())
    

    forms.py

    from django import forms
    from .models import Order
    
    class OrderCreateForm(forms.ModelForm):
        class Meta:
            model = Order
            fields = ['first_name', 'last_name', 'email', 'address', 'postal_code', 'city']
    

    create.html

    {% extends "shop/base.html" %}
    
    {% block title %}
        Checkout
    {% endblock %}
    
    {% block content %}
        <h1>Checkout</h1>
    
        <form action="." method="post" class="order-form">
            {{ form.as_p }}
            <p><input type="submit" value="Place order"></p>
            {% csrf_token %}
        </form>
    {% endblock %}
    

    Any suggestions are welcome.Please help.

    UPDATE

    How to add select option ?