Skip to main content

Grouped CheckboxSelectMultiple in Django template

from itertools import groupby
from django import forms
from django.forms.models import ModelChoiceIterator, ModelMultipleChoiceField
from .models import Feature, Widget
class GroupedModelMultipleChoiceField(ModelMultipleChoiceField):

    def __init__(self, group_by_field, group_label=None, *args, **kwargs):
        """
        ``group_by_field`` is the name of a field on the model
        ``group_label`` is a function to return a label for each choice group

        """
        super(GroupedModelMultipleChoiceField, self).__init__(*args, **kwargs)
        self.group_by_field = group_by_field
        if group_label is None:
            self.group_label = lambda group: group
        else:
            self.group_label = group_label

    def _get_choices(self):
        if hasattr(self, '_choices'):
            return self._choices
        return GroupedModelChoiceIterator(self)
    choices = property(_get_choices, ModelMultipleChoiceField._set_choices)

class GroupedModelChoiceIterator(ModelChoiceIterator):

    def __iter__(self):
        """Now yields grouped choices."""            
        if self.field.empty_label is not None:
            yield ("", self.field.empty_label)
        for group, choices in groupby(
                self.queryset.all(),
                lambda row: getattr(row, self.field.group_by_field)):
            if group is None:
                for ch in choices:
                    yield self.choice(ch)
            else:
                yield (
                    self.field.group_label(group),
                    [self.choice(ch) for ch in choices])
class WidgetForm(forms.ModelForm):
    class Meta:
        model = Widget
        fields = ['features',]

    def __init__(self, *args, **kwargs):
        super(WidgetForm, self).__init__(*args, **kwargs)
        self.fields['features'] = GroupedModelMultipleChoiceField(
            group_by_field='category',
            queryset=Feature.objects.all(),
            widget=forms.CheckboxSelectMultiple(),
            required=False)

Comments

Popular posts from this blog

HTML Emailing in ZF2

<?php namespace Application\Model; use Zend\Mail\Message; use Zend\Mime\Message as MimeMessage; use Zend\Mime\Part as MimePart; use Zend\Mail\Transport\Sendmail as SendmailTransport; use Zend\Mail\Transport\Smtp as SmtpTransport; use Zend\Mail\Transport\SmtpOptions; use Zend\View\Renderer\PhpRenderer; use Zend\View\Resolver\TemplatePathStack; use Zend\View\Model\ViewModel; use Zend\View\Model\ModelInterface; class ApiEmail extends ApiInterface {    protected $From = "XXXXX@gmail.com";    protected $FromName = "XXXX";    protected $To = "" ;    protected $Subject = "" ;    protected $Body = "" ;    protected $Cc = "XXXXXX@gmail.com";    protected $Bcc = "XXXXX@gmail.com" ;    protected $ReplyTo = "XXXX@gmail.com" ;    protected $Sender = "" ;    protected $Encoding = "UTF-8" ;    protected $MESSAGE ; // getter setter    public fun

How to start working with Django web framework

 Django is a powerful web framework for Python that makes it easy to build web applications quickly. Here are some steps you can follow to start learning Django programming: Install Python: Django requires Python to be installed on your machine. If you don ' t already have Python installed, you can download it from the official Python website (https://www.python.org/downloads/). Install Django: Once you have Python installed, you can use the pip package manager to install Django. Open a terminal or command prompt and type the following command: pip install django Create a new Django project: To create a new Django project, open a terminal or command prompt and navigate to the directory where you want to store your project. Then run the following command: django - admin startproject myproject Replace myproject with the name you want to give to your project. This will create a new Django project with the specified name in the current directory. Run the development

How to setup django | django installation ubuntu

Introduction to Django 1.     High level web framework 1.     Basic modules, classes, and tools to quickly develop and deploy web apps 2.     Contains an ORM (Object-Relational Mapper) that allows for the use of standard Python language syntax when interfacing with a back-end database. 1.     Developer need not learn SQL, DDL, etc! 3.     Provides a template framework that allows HTML, XML, and other “documents” to be converted into “templates”, which can then be converted to “output” via a wide range of substitution techniques. 4.     Elegant URL support (fancy, beautiful URL's, no “?blah=blah”, etc.) 5.     Multi-lingual 2.     Fast and easy to use, robust, flexible, and lots of contributed components available! 1.     Built in administrative interface to manage data models. 2.     Built-in authentication/access control components 3.     Contributed Installing & Configuring Django Components 1.     Django can be downloaded from http://w