Login

ModelForm Class saving m2m

Author:
ckarrie2
Posted:
October 11, 2011
Language:
Python
Version:
1.3
Score:
1 (after 1 ratings)

Your model:

class TicketItem(models.Model):
    hours = models.DecimalField(decimal_places=2, max_digits=6)
    day = models.DateField()
    order = models.ForeignKey(Order)
    tickets = models.ManyToManyField(Ticket)

Now you want to auto save m2m fields in your forms.TicketItemCreateForm:

  1. inherit from m2mForm-Class
  2. define m2m_field(s)

Example:

class TicketItemCreateForm(m2mForm):     
    m2m_field = 'tickets'    
    class Meta:
        model = models.TicketItem
 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.