I’m trying to create a form where a logged in user (PrincipalGuest
) can update themselves but also multiple guests (AccompanyingGuest
). I want an entire form with the attending
and dietary_restrictions
field embedded within a form, not just the ModelMultipleChoiceField
.
models.py
class Guest(models.Model):
""" """
attending = models.ManyToManyField("itinerary.Event", blank=True)
dietary_restrictions = models.ManyToManyField(DietaryRestrictions, blank=True)
last_modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class PrincipalGuest(Guest, AbstractUser):
""" """
USERNAME_FIELD = "email"
REQUIRED_FIELDS = []
username = None
email = models.EmailField(_("email address"), unique=True)
phone_number = PhoneNumberField(null=True)
address = AddressField(on_delete=models.CASCADE, null=True)
objects = PrincipalGuestManager()
@property
def name(self):
return self.first_name + " " + self.last_name
def __str__(self):
return self.name
class AccompanyingGuest(Guest):
""" """
principal = models.ForeignKey(
PrincipalGuest, related_name="accompanying_guests", on_delete=models.CASCADE
)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
is_under_ten = models.BooleanField(default=False)
@property
def name(self):
return self.first_name + " " + self.last_name
def __str__(self):
return self.name
views.py
class RendezvousFormView(SuccessMessageMixin, UpdateView):
template_name = "rsvp.html"
form_class = RendezvousForm
success_url = "/rsvp"
success_message = "Thank you for your RSVP"
def get_object(self):
return self.request.user
forms.py
class RendezvousForm(ModelForm):
""" """
first_name = CharField(
label="", widget=TextInput(attrs={"placeholder": "First Name"})
)
last_name = CharField(
label="", widget=TextInput(attrs={"placeholder": "Last Name"})
)
email = CharField(label="", widget=TextInput(attrs={"placeholder": "Email"}))
phone_number = CharField(
label="", widget=TextInput(attrs={"placeholder": "Phone Number"})
)
address = AddressField(
label="", widget=AddressWidget(attrs={"placeholder": "Home Address"})
)
attending = ModelMultipleChoiceField(
queryset=Event.objects.all(),
required=False,
label="Will be attending",
widget=CheckboxSelectMultiple(attrs={"class": "h4"}),
)
dietary_restrictions = ModelMultipleChoiceField(
DietaryRestrictions.objects.all(),
required=False,
widget=CheckboxSelectMultiple(attrs={"class": "h4"}),
)
class Meta:
model = PrincipalGuest
fields = [
"first_name",
"last_name",
"email",
"phone_number",
"address",
"attending",
"dietary_restrictions",
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.label_suffix = ""
self.fields["accompanying_guests"] = ModelMultipleChoiceField(
queryset=AccompanyingGuest.objects.filter(principal=kwargs["instance"])
)