• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

How to Initialize Default Multiple Choice Field in Django Form?

Aniruddha Chaudhari/2838/0
Django

In the earlier Django tutorial, I have explained- how to create a model, form, and template.

In this tutorial, we are going to learn how to create a Django form with a multi-choice field (multiple choice options) and select initial values by default.

Here is a short glimpse of the Django form we are going to create in this tutorial.

multi select checkbox in Django with default initial values

I will explain this with an example.

Create Django Form with MultipleChoiceField

Follow the steps one by one.

Step 1: Create model with CharField()

We are going to create a model which has a field of type CharField.

Update models.py.

from django.db import models

class Contact(models.Model):
    prefered_contact= models.CharField(max_length=120, choices=CONTACT_PREFERENCE, default='')

Step 2: Define Django Form

Create a Django form with the form field of type MultipleChoiceField.

Here choices are the options for the multi-select checkbox.

Update forms.py.

CONTACT_PREFERENCE = [
    ('email', 'Email'),
    ('chat', 'Chat'),'
    ('call', 'Call'), 
]

class ContactForm(forms.ModelForm):
    prefered_contact = forms.MultipleChoiceField(
        choices=CONTACT_PREFERENCE, 
        widget=forms.CheckboxSelectMultiple()
    )

    class Meta:
        model = Contact
        fields = ('prefered_contact',)

Step 3: Show Django Form in Template

You can use a Django template tag to display the HTML form.

{{ form.as_p }}

It will show the Django form with a multi-select checkbox. This is pretty easy.

Now, what happens when you submit the form?

When you submit the form, the values of the selected options are stored as a list of values. But, this list is saved in the model as a Python string. You can check that in the Django admin panel.

Select Default Checkbox Options in Django Form

In this Django form, we want to show the default options selected.

In the above example, when the user opens the form, the ’email’ and ‘chat’ options should be selected by default.

Update the Django view by setting the initial values for the checkbox field while creating an instance of the Django form. The initial value to the multiple-choice fields should be the list of values.

def land_demand_form(request):
    form = ContactForm(request.POST or None, initial={"prefered_contact": ['email', 'chat']})
    context= {'form': form}

Now, it will show the initial values (’email’ and ‘chat’) populated on the Django form.

Note: Property initial works when you use the {{ form.as_p }} template tag to create the Django form. If you are customizing a Django form template manually, this method does not work.

In that case, pass the list of the default selected options as a new context variable (says ‘selected_contact’) to the Django template.

This is a bit tricky.

def land_demand_form(request):
    form = ContactForm(request.POST or None)
    context= {'form': form, selected_contact=['email', 'chat']}

And update the Django template to show the multi-select checkbox options.

{% for value, text in form.prefered_contact.field.choices %}
    <label for="id_prefered_contact_{{ forloop.counter0 }}">
    <input type="checkbox" name="prefered_contact" value="{{ value }}" id="id_prefered_contact_{{ forloop.counter0 }}" {% if value in selected_contact %} checked="checked"{% endif %}> {{ text }}
    </label>
    <br>
 {% endfor %}

You are done!

How to create a Django form to update MultipleChoiceField fields?

If you are allowing users to update or edit the form, fetch the object from the model (one that the user has already submitted). It will return the Python list of the earlier selected options.

Now, instead of hardcoding the initial (default) value, pass the list of selected options and populate them in the HTML form.

Update the Django view as follow.

import ast

def land_demand_form(request):
    obj= get_object_or_404(Contact, user=request.user)
    res = ast.literal_eval(obj.prefered_contact)
    form = ContactForm(request.POST or None, initial={"prefered_contact": res})
    context= {'form': form}

Here, obj.pregeted_contact returns, the string representation of the list. We are using ast module to convert the string representation of the Python list into the actual Python list.

With this, users can edit or modify the earlier selected options.

If you have any doubt, let me know in the comment section below.

Python Interview Questions eBook

Django
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Leave a Reply Cancel reply

Prerequisite for Django

Learn Python Basics

Django Tutorials

Why Django?

Django- Create Your First Project

Django- Adding CSS/Static Files

Django- Use/Load Static Files

Django- Create Form

Django- Create Input-Tags

Django- Display Message on Form Submit

Django- MultipleChoiceField in Form

Django- Read Model Data (order_by)

Django- Read First/Last Queryset Object

Django- Update Model Field

Django- Signals

Django- Create TextField in Form

Django- Add Model to Admin Site

Django- Customize Admin Site

Django- Understanding Model User

Django- Registration/Signup Form

Django- Form Layout with Widget-Tweaks

Django- OneToOneField in Model

Django- Foreign Key & Reverse Lookup

Django- Custom Template Filters

Django- Interactive Shell

Django- Social Login

Django- Deploy and Host [FREE] 🔥

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard