[Answered ]-Django ModelForms: Seeding a FK related field in the form

0👍

Turns out I was overly complicating this.

All I needed to do was modify the form_valid method for Django’s GCBV FormView to this:

workshop/views.py

from django.views.generic.edit import FormView
from workshop.models import Workshop, WorkshopAttendee
from workshop.forms import WorkshopAttendeeForm
from django.http import HttpResponseRedirect

class WorkshopAttendeeFormView(FormView):

    def form_valid(self, form):

        self.object = form.save(commit=False)
        self.object.workshop = Workshop.objects.filter(slug=self.kwargs['slug'])[0]
        self.object.save()
        return HttpResponseRedirect(self.get_success_url())

Which basically does not save the form on submit, but instead overrides it and first updates the object it is about to save (the WorkshopAttendee object) with the relevant Workshop (based on the Workshop slug field, which is unique), then saves the updated object (self.object.save) and kicks me to the success url.

Big thanks to @init3 for his helpful pointers. Much appreciated.

👤tatlar

2👍

You don’t need to pass the PK – you got it already in your URL as the slug.

So let’s say this is your URL: http://example.com/workshops/awesome-workshop-slug/sign_in/
Your urls.py should look like this:

url(r'^workshop/(?P<workshop_slug>\w+)/sign_in/$',
        # ../workshops/awesome-workshop-slug/sign_in/
        view = 'workshop_signin',
        name = 'workshop-signin',
    ),

Ok, in your views.py you’re able to do this:

@login_required
def workshop_signin(request, workshop_slug, template='workshop/sign_in.html'):
    """Register user to workshop."""
    form = WorkshopForm()
    workshop = Workshop.objects.filter(slug=workshop_slug)[0]

    if request.method == 'POST':
        form = WorkshopForm(request.POST, instance=workshop)
        if form.is_valid():
            messages.info(request, 'Yay!')


    kwargs = {
        'workshop_form': form,
    }
    return render_to_response(template, kwargs, context_instance=RequestContext(request))

*untested quick and dirty code

Leave a comment