2👍
✅
In this case I wouldn’t use a ModelForm
because they are for the case that you want to represent one Model instance by one Form. Here you want to produce multiple instances with one form. So just write a common form with a custom field (there is acutally an example just for this in the Django docs) and maybe a custom save method:
from django import forms
from django.core.validators import validate_email
class MultiEmailField(forms.Field):
def to_python(self, value):
"Normalize data to a list of strings."
# Return an empty list if no input was given.
if not value:
return []
return value.split(',')
def validate(self, value):
"Check if value consists only of valid emails."
# Use the parent's handling of required fields, etc.
super(MultiEmailField, self).validate(value)
for email in value:
validate_email(email)
class EmailListForm(forms.Form):
emails = forms.MulitEmailField()
network = forms.ModelChoiceField(queryset=Network.objects.all())
# save the emails to the db
def save(self):
for email in self.cleaned_data.get('emails'):
EmailList.objects.create(email = email,
network=self.network)
# in views
def email(request):
if request.method == 'POST':
form = EmailListForm(request.POST)
if form.is_valid():
form.save()
return redirect(...somewhere...)
else:
form = EmailListForm()
return render(request, 'some/template.html', { 'form': form }
Source:stackexchange.com