I have a model that has additional information I need to attach to the user's if they are part of a specific group. I have built a simple CreateView in order to test this working. Unfortunetly, it's not saving all the information in the second model. This is my first time using betterforms, and I followed the docs. However it looks like I'm missing something. Here is my current code:
Forms.py:
# Operator Creation Form
class OperatorProfileForm(forms.ModelForm):
class Meta:
model = OperatorProfile
fields = ('cdl', 'endorsement', 'cdl_expiration')
class UserCreationMultiForm(MultiModelForm):
form_classes = {
'user': UserCreationForm,
'profile': OperatorProfileForm,
}
# Save the user first, because the profile needs a user before it
# can be saved.
def save(self, commit=True):
objects = super(UserCreationMultiForm, self).save(commit=False)
if commit:
user = objects['user']
user.save()
profile = objects['profile']
profile.user = user
profile.save()
return objects
Views.py:
class IndexView(TemplateView):
template_name = 'pages/index.html'
class OperatorCreateView(CreateView):
model = OperatorProfile
template_name = 'pages/operatorprofile_form.html'
form_class = UserCreationMultiForm
success_url = reverse_lazy('index')
Models.py:
class CDL(models.Model):
cdl_type = models.CharField(max_length=10)
description = models.TextField(max_length=255, blank=True)
def __str__(self):
return self.cdl_type
class Endorsement(models.Model):
endorsement_type = models.CharField(max_length=10)
description = models.TextField(max_length=255, blank=True)
def __str__(self):
return self.endorsement_type
class OperatorProfile(models.Model):
user = models.ForeignKey('auth.User', on_delete=models.CASCADE)
cdl = models.ManyToManyField('CDL')
endorsement = models.ManyToManyField('Endorsement')
cdl_expiration = models.DateField(default=timezone.now)
def __str__(self):
return str(self.user)
Currently it's not saving the ForeignKeys in the OperatorProfile model, but the other settings are saving just fine. Any input would be greatly appreciated.
Well...i'm an idiot. I forgot about save_m2m(). Here is the solution for people who are wondering.
forms.py:
Views.py: