ModelForm Class saving m2m

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class m2mForm(forms.ModelForm):
    """
    m2m_field = Fieldname of your m2m Field
    m2m_fields = supports multiple m2m Fields
    """
    m2m_field = ''
    m2m_fields = []
    
    def save(self, commit=True):
        """
        Saving m2m
        """
        instance = super(m2mForm, self).save(commit=True)
        if self.m2m_field:
            self.m2m_fields = [self.m2m_field]
            
        for field in self.m2m_fields:
            m2mfield = getattr(instance, field)
            for obj in self.cleaned_data.get(field):
                m2mfield.add(obj)
        
        if commit:
            instance.save()
            #self.save_m2m()
            
        return instance

More like this

  1. Command to dump data as a python script by willhardy 5 years, 10 months ago
  2. Add attrs automaticlly through ModelForm field max_length by lettoo 2 years, 3 months ago
  3. Modeli18n by pavl 3 years, 10 months ago
  4. Group results by a range of values in admin sidebar by wgollino 6 years, 2 months ago
  5. load m2m fields objects by dirol 3 years, 10 months ago

Comments

(Forgotten your password?)