snipt

Ctrl+h for KB shortcuts
Notice: Snipt is moving away from free accounts on May 1st, 2014. Read more about the transition here.
#25406

Python

Symmetrical ManyToMany Filter Horizontal in Django Admin

"""
When adding a many-to-many (m2m) relationship in Django, you can use a nice filter-style multiple select widget to manage entries. However, Django only lets you edit the m2m relationship this way on the forward model. The only built-in method in Django to edit the reverse relationship in the admin is through an InlineModelAdmin.

Below is an example of how to create a filtered multiple select for the reverse relationship, so that editing entries is as easy as in the forward direction.
"""

### pizza/models.py ###

from django.db import models

class Pizza(models.Model):
  name = models.CharField(max_length=50)
  toppings = models.ManyToManyField(Topping, related_name='pizzas')

class Topping(models.Model):
  name = models.CharField(max_length=50)

### pizza/admin.py ###

from django import forms
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin.widgets import FilteredSelectMultiple

from .models import Pizza, Topping

class PizzaAdmin(admin.ModelAdmin):
  filter_horizonal = ('toppings',)

class ToppingAdminForm(forms.ModelForm):
  pizzas = forms.ModelMultipleChoiceField(
    queryset=Pizza.objects.all(), 
    required=False,
    widget=FilteredSelectMultiple(
      verbose_name=_('Pizzas'),
      is_stacked=False
    )
  )

  class Meta:
    model = Topping

  def __init__(self, *args, **kwargs):
    super(ToppingAdminForm, self).__init__(*args, **kwargs)

    if self.instance and self.instance.pk:
      self.fields['pizzas'].initial = self.instance.pizzas.all()

  def save(self, commit=True):
    topping = super(ToppingAdminForm, self).save(commit=False)

    if commit:
      topping.save()

    if topping.pk:
      topping.pizzas = self.cleaned_data['pizzas']
      self.save_m2m()

    return topping

class ToppingAdmin(admin.ModelAdmin):
  form = ToppingAdminForm

admin.site.register(Pizza, PizzaAdmin)
admin.site.register(Topping, ToppingAdmin)
https://snipt.net/embed/11061d9a8c3998e703411cbad0e25402/
https://snipt.net/raw/11061d9a8c3998e703411cbad0e25402/
11061d9a8c3998e703411cbad0e25402
python
Python
66
2014-04-23T18:51:09
True
False
/api/public/snipt/25406/
symmetrical-manytomany-filter-horizontal-in-django-admin
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><a href="#L-1"> 1</a> <a href="#L-2"> 2</a> <a href="#L-3"> 3</a> <a href="#L-4"> 4</a> <a href="#L-5"> 5</a> <a href="#L-6"> 6</a> <a href="#L-7"> 7</a> <a href="#L-8"> 8</a> <a href="#L-9"> 9</a> <a href="#L-10">10</a> <a href="#L-11">11</a> <a href="#L-12">12</a> <a href="#L-13">13</a> <a href="#L-14">14</a> <a href="#L-15">15</a> <a href="#L-16">16</a> <a href="#L-17">17</a> <a href="#L-18">18</a> <a href="#L-19">19</a> <a href="#L-20">20</a> <a href="#L-21">21</a> <a href="#L-22">22</a> <a href="#L-23">23</a> <a href="#L-24">24</a> <a href="#L-25">25</a> <a href="#L-26">26</a> <a href="#L-27">27</a> <a href="#L-28">28</a> <a href="#L-29">29</a> <a href="#L-30">30</a> <a href="#L-31">31</a> <a href="#L-32">32</a> <a href="#L-33">33</a> <a href="#L-34">34</a> <a href="#L-35">35</a> <a href="#L-36">36</a> <a href="#L-37">37</a> <a href="#L-38">38</a> <a href="#L-39">39</a> <a href="#L-40">40</a> <a href="#L-41">41</a> <a href="#L-42">42</a> <a href="#L-43">43</a> <a href="#L-44">44</a> <a href="#L-45">45</a> <a href="#L-46">46</a> <a href="#L-47">47</a> <a href="#L-48">48</a> <a href="#L-49">49</a> <a href="#L-50">50</a> <a href="#L-51">51</a> <a href="#L-52">52</a> <a href="#L-53">53</a> <a href="#L-54">54</a> <a href="#L-55">55</a> <a href="#L-56">56</a> <a href="#L-57">57</a> <a href="#L-58">58</a> <a href="#L-59">59</a> <a href="#L-60">60</a> <a href="#L-61">61</a> <a href="#L-62">62</a> <a href="#L-63">63</a> <a href="#L-64">64</a> <a href="#L-65">65</a></pre></div></td><td class="code"><div class="highlight"><pre><span id="L-1"><a name="L-1"></a><span class="sd">&quot;&quot;&quot;</span> </span><span id="L-2"><a name="L-2"></a><span class="sd">When adding a many-to-many (m2m) relationship in Django, you can use a nice filter-style multiple select widget to manage entries. However, Django only lets you edit the m2m relationship this way on the forward model. The only built-in method in Django to edit the reverse relationship in the admin is through an InlineModelAdmin.</span> </span><span id="L-3"><a name="L-3"></a> </span><span id="L-4"><a name="L-4"></a><span class="sd">Below is an example of how to create a filtered multiple select for the reverse relationship, so that editing entries is as easy as in the forward direction.</span> </span><span id="L-5"><a name="L-5"></a><span class="sd">&quot;&quot;&quot;</span> </span><span id="L-6"><a name="L-6"></a> </span><span id="L-7"><a name="L-7"></a><span class="c">### pizza/models.py ###</span> </span><span id="L-8"><a name="L-8"></a> </span><span id="L-9"><a name="L-9"></a><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span> </span><span id="L-10"><a name="L-10"></a> </span><span id="L-11"><a name="L-11"></a><span class="k">class</span> <span class="nc">Pizza</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span> </span><span id="L-12"><a name="L-12"></a> <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span> </span><span id="L-13"><a name="L-13"></a> <span class="n">toppings</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">Topping</span><span class="p">,</span> <span class="n">related_name</span><span class="o">=</span><span class="s">&#39;pizzas&#39;</span><span class="p">)</span> </span><span id="L-14"><a name="L-14"></a> </span><span id="L-15"><a name="L-15"></a><span class="k">class</span> <span class="nc">Topping</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span> </span><span id="L-16"><a name="L-16"></a> <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span> </span><span id="L-17"><a name="L-17"></a> </span><span id="L-18"><a name="L-18"></a><span class="c">### pizza/admin.py ###</span> </span><span id="L-19"><a name="L-19"></a> </span><span id="L-20"><a name="L-20"></a><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">forms</span> </span><span id="L-21"><a name="L-21"></a><span class="kn">from</span> <span class="nn">django.contrib</span> <span class="kn">import</span> <span class="n">admin</span> </span><span id="L-22"><a name="L-22"></a><span class="kn">from</span> <span class="nn">django.utils.translation</span> <span class="kn">import</span> <span class="n">ugettext_lazy</span> <span class="k">as</span> <span class="n">_</span> </span><span id="L-23"><a name="L-23"></a><span class="kn">from</span> <span class="nn">django.contrib.admin.widgets</span> <span class="kn">import</span> <span class="n">FilteredSelectMultiple</span> </span><span id="L-24"><a name="L-24"></a> </span><span id="L-25"><a name="L-25"></a><span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Pizza</span><span class="p">,</span> <span class="n">Topping</span> </span><span id="L-26"><a name="L-26"></a> </span><span id="L-27"><a name="L-27"></a><span class="k">class</span> <span class="nc">PizzaAdmin</span><span class="p">(</span><span class="n">admin</span><span class="o">.</span><span class="n">ModelAdmin</span><span class="p">):</span> </span><span id="L-28"><a name="L-28"></a> <span class="n">filter_horizonal</span> <span class="o">=</span> <span class="p">(</span><span class="s">&#39;toppings&#39;</span><span class="p">,)</span> </span><span id="L-29"><a name="L-29"></a> </span><span id="L-30"><a name="L-30"></a><span class="k">class</span> <span class="nc">ToppingAdminForm</span><span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">ModelForm</span><span class="p">):</span> </span><span id="L-31"><a name="L-31"></a> <span class="n">pizzas</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">ModelMultipleChoiceField</span><span class="p">(</span> </span><span id="L-32"><a name="L-32"></a> <span class="n">queryset</span><span class="o">=</span><span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">(),</span> </span><span id="L-33"><a name="L-33"></a> <span class="n">required</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span> </span><span id="L-34"><a name="L-34"></a> <span class="n">widget</span><span class="o">=</span><span class="n">FilteredSelectMultiple</span><span class="p">(</span> </span><span id="L-35"><a name="L-35"></a> <span class="n">verbose_name</span><span class="o">=</span><span class="n">_</span><span class="p">(</span><span class="s">&#39;Pizzas&#39;</span><span class="p">),</span> </span><span id="L-36"><a name="L-36"></a> <span class="n">is_stacked</span><span class="o">=</span><span class="bp">False</span> </span><span id="L-37"><a name="L-37"></a> <span class="p">)</span> </span><span id="L-38"><a name="L-38"></a> <span class="p">)</span> </span><span id="L-39"><a name="L-39"></a> </span><span id="L-40"><a name="L-40"></a> <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span> </span><span id="L-41"><a name="L-41"></a> <span class="n">model</span> <span class="o">=</span> <span class="n">Topping</span> </span><span id="L-42"><a name="L-42"></a> </span><span id="L-43"><a name="L-43"></a> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span> </span><span id="L-44"><a name="L-44"></a> <span class="nb">super</span><span class="p">(</span><span class="n">ToppingAdminForm</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span> </span><span id="L-45"><a name="L-45"></a> </span><span id="L-46"><a name="L-46"></a> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">instance</span> <span class="ow">and</span> <span class="bp">self</span><span class="o">.</span><span class="n">instance</span><span class="o">.</span><span class="n">pk</span><span class="p">:</span> </span><span id="L-47"><a name="L-47"></a> <span class="bp">self</span><span class="o">.</span><span class="n">fields</span><span class="p">[</span><span class="s">&#39;pizzas&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">initial</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">instance</span><span class="o">.</span><span class="n">pizzas</span><span class="o">.</span><span class="n">all</span><span class="p">()</span> </span><span id="L-48"><a name="L-48"></a> </span><span id="L-49"><a name="L-49"></a> <span class="k">def</span> <span class="nf">save</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">commit</span><span class="o">=</span><span class="bp">True</span><span class="p">):</span> </span><span id="L-50"><a name="L-50"></a> <span class="n">topping</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">ToppingAdminForm</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="n">commit</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span> </span><span id="L-51"><a name="L-51"></a> </span><span id="L-52"><a name="L-52"></a> <span class="k">if</span> <span class="n">commit</span><span class="p">:</span> </span><span id="L-53"><a name="L-53"></a> <span class="n">topping</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> </span><span id="L-54"><a name="L-54"></a> </span><span id="L-55"><a name="L-55"></a> <span class="k">if</span> <span class="n">topping</span><span class="o">.</span><span class="n">pk</span><span class="p">:</span> </span><span id="L-56"><a name="L-56"></a> <span class="n">topping</span><span class="o">.</span><span class="n">pizzas</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">cleaned_data</span><span class="p">[</span><span class="s">&#39;pizzas&#39;</span><span class="p">]</span> </span><span id="L-57"><a name="L-57"></a> <span class="bp">self</span><span class="o">.</span><span class="n">save_m2m</span><span class="p">()</span> </span><span id="L-58"><a name="L-58"></a> </span><span id="L-59"><a name="L-59"></a> <span class="k">return</span> <span class="n">topping</span> </span><span id="L-60"><a name="L-60"></a> </span><span id="L-61"><a name="L-61"></a><span class="k">class</span> <span class="nc">ToppingAdmin</span><span class="p">(</span><span class="n">admin</span><span class="o">.</span><span class="n">ModelAdmin</span><span class="p">):</span> </span><span id="L-62"><a name="L-62"></a> <span class="n">form</span> <span class="o">=</span> <span class="n">ToppingAdminForm</span> </span><span id="L-63"><a name="L-63"></a> </span><span id="L-64"><a name="L-64"></a><span class="n">admin</span><span class="o">.</span><span class="n">site</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">Pizza</span><span class="p">,</span> <span class="n">PizzaAdmin</span><span class="p">)</span> </span><span id="L-65"><a name="L-65"></a><span class="n">admin</span><span class="o">.</span><span class="n">site</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">Topping</span><span class="p">,</span> <span class="n">ToppingAdmin</span><span class="p">)</span> </span></pre></div> </td></tr></table>
django, django-admin, m2m, manytomany