I am creating a form where a someone enters a network, location, and administrators of the network. This is my model —
class Administrator(models.Model):
email = models.EmailField()
name = models.CharField(max_length=100, blank=True)
class Network(models.Model):
name = models.CharField(max_length=50)
location = models.CharField(max_length=50)
administrators = models.ManyToManyField(Administrator, blank=True)
How could I create a form such that when the site admin adds an administrator to a network, it will immediately create that entry in the Administrator class and then link up to that in the administrators column?
For custom processing of your form objects use
form.save(commit=False):from: https://docs.djangoproject.com/en/1.0/topics/forms/modelforms/#the-save-method
So if you have a
NetworkFormyou could usecommit=Falseand then check if your administrator already exists or if he needs to be created.get_or_createis really handy for this.Then you could set
administratoron your form to the newly created or fetched administrator-instance and save the form (usingform.save()andform.save_m2m()).