Is there a way to directly update a M2M relationship, other than by deleting the old_object & then adding a new_object?
This is what I currently have to add a new object —
if 'Add School' in request.POST.values():
form = EducationForm(request.POST)
if form.is_valid and request.POST['school']:
school_object = form.save()
profile.educations.add(school_object)
profile.save()
return redirect('edit_education')
And this what I’m trying to do —
if 'Save Changes' in request.POST.values():
form = EducationForm(request.POST)
if form.is_valid and request.POST['school']:
new_school_object = form.save(commit=False)
old_school_object = Education.objects.get(id = request.post['id'])
# profile.educations.get(old_school_object).update(new_school_object) # ?
profile.save()
return redirect('edit_education')
And here are my models —
class Education(models.Model):
school = models.CharField(max_length=100)
class_year = models.IntegerField(max_length=4, blank=True, null=True, choices=YEAR)
degree = models.CharField(max_length=100, blank=True, null=True)
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
...
educations = models.ManyToManyField(Education)
Educationis probably something personal to oneUserProfile, so you should use aForeignKeyinstead of M2M:(and optionally use model formsets: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#model-formsets )
If
Educationis actually shared between users, it should not be possible for one user to modify/update it – since other users are using it as well! consider users Alice and Bob, both learning for BSc in USC class of 2011. If Alice changes this to MA, Bob education will change as well!Another tip: In your templates use
<input type="submit" name="save" value="..."/>and<input type="submit" name="add" value="..."/>and in yourifs check for the keys “save” or “add” instead.