Search code examples
djangoformsforeign-keyswagtail

How to link two forms (wagtail form and django form) with a foreign key?


I'm using a django form in conjunction with a wagtail form. The django form will record some fields that will be on any form of this type: name, email and the wagtail form will record extra data defined by the form page creator specific to that instance.

I've overloaded the serve method to capture both sets of data and I can process both forms, but I'm stuck when trying to add the logic to relate the form contents to each other so that when one submission set is deleted, the other set will be as well. I think what I need is a foreign key.

The following code fails at form_submission.event_submission = a.id where I'd like to take the id from the wagtail form submission and add that as a foreign key to the django form, so that when the wagtail form portion is deleted, the other is deleted as well, and so that I can have a usable link between the two form submissions.

def serve(self, request, *args, **kwargs):
    if request.method == 'POST':
        form = EventSignupForm(request.POST)
        wagtail_form = self.get_form(request.POST, request.FILES, page=self, user=request.user)

        if form.is_valid() and wagtail_form.is_valid():
            a = self.process_form_submission(wagtail_form)
            form_submission = form.save(commit=False)
            form_submission.event_submission = a.id
            form_submission.save()
            return self.render_landing_page(request, form_submission, *args, **kwargs)
    else:
        form = EventSignupForm()
        wagtail_form = self.get_form(page=self, user=request.user)

    context = self.get_context(request)
    context['form'] = form
    context['wagtail_form'] = wagtail_form
    return TemplateResponse(
        request,
        self.get_template(request),
        context
    )

The form submission class and django model form looks like this. I think the ForeignKey I have in the Model isn't right, but I don't know. Any help?

class EventFormSubmission(AbstractFormSubmission):
    cancellation_id = models.CharField(max_length=7)

class EventSignup(models.Model):
    """
    A model to contain signup info for an event: name, email.
    """
    event_submission = models.ForeignKey(EventFormSubmission, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    email = models.EmailField()

Solution

  • I solved this by adding the extra fields I wanted (name, email) to the EventFormSubmission and then using a regular django form (not a ModelForm) to collect these pieces of information.