Change: Saving ManyToMany Relationships

created on Oct. 24, 2012, 11:29 p.m. by Hevok & updated on Oct. 25, 2012, 12:39 a.m. by Hevok

In order to save ManyToMany relationships of model (e.g. data tags of an entry), the respective clean field method of the model form can be overwritten like this: ::

nano models.py
from django.db import models


class Tag(models.Mode):
    name = models.CharField(max_lengt=20)

class Entry(models.Model):
    title = models.CharField(max_length=100)
    date = models.DateField()
    tags = models.ManyToManyField(Tag)


nano forms.py
from django.forms import models

from models import Entry, Tag


class EntryForm(models.ModelForm):

    def clean_tags(self):
        tags = self.cleaned_data.get('tags', None)
        clean_tags = []
        tags = [tag.sprit() for tag in tags.split(',') if tags]
        for tag in tags:
            t, created = Tag.objects.get_or_create(title=tag)
            t.count = F('count') + 1
            t.user.add(self.cleaned_data['user'])
            t.save()
            clean_tags.append(t)
        return clean_tags

    class meta:
        model = Entry
m2m.png

Tags: m2m, save, django
Categories: Tutorial
Parent: Web Framework

Comment: Two blank lines separting imports from classes.

See entry | Admin

Comment on This Data Unit