I am building a user profile in django, where I want the user to enter his skill set. The skill field is a ManyToMany
field to a model name Skills
. Below is shown the models.py
file
class UserProfile(models.Model):
name = models.CharField(max_length = 300, null = True, blank=True)
location = models.CharField(max_length=500, null=True, blank=True)
birthday = models.DateField(null = True, blank = True)
user = models.ForeignKey(User, unique=True)
skills = models.ManyToManyField(Skill, blank=True, null=True)
class Skill(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return u'%s' %(self.name)
As you can see all the fields are set null=True
. This is because I am keeping the fields empty and want the user to input them as and when he/she wants to. So I am updating all these fields using AJAX call. I have managed to edit all the other fields, but I do not know how can I edit a M2M field
I can get a list of all the skills linked to a profile using profile.skills.all()
but I do not know how to update this list. I basically want to add or remove skill objects from this list. I think there is something in the django.db.models.fields.related.ManyRelatedManager
using which I can edit the field
Any help is really appreciated. I have not found anything at all on this subject. There is some information about editing this field using a ModelForm but nothing about editing the individual field.
To edit the m2m intermediary table, use the add
and remove
methods on the ManyRelatedManager
.
It's true, the hardest things to google on the django docs are manytomanyfield and other continuous strings. I've blogged about formfield_for_manytomany
solely to appear in search results for myself.