Search code examples
djangoformsdjango-generic-views

How to pass ForeignKey value into initial data for Django form


I have a model like this:

class Job(models.Model):
    slug = models.SlugField()

class Application(models.Model):
    job = models.ForeignKey(Job)

And a view like this:

class ApplicationCreateView(CreateView):
    model = Application

A user will view the job object (/jobs/<slug>/), then complete the application form for the job (/jobs/<slug>/apply/).

I'd like to pass application.job.slug as the initial value for the job field on the application form. I'd also like for the job object to be put in context for the ApplicationCreateView (to tell the user what job they're applying for).

How would I go about doing this in my view?


Solution

  • I ended up doing the following in a function on my class:

    class ApplicationCreateView(CreateView):
        model = Application
        form_class = ApplicationForm
        success_url = 'submitted/'
    
        def dispatch(self, *args, **kwargs):
            self.job = get_object_or_404(Job, slug=kwargs['slug'])
            return super(ApplicationCreateView, self).dispatch(*args, **kwargs)
    
        def form_valid(self, form):
            #Get associated job and save
            self.object = form.save(commit=False)
            self.object.job = self.job
            self.object.save()
    
            return HttpResponseRedirect(self.get_success_url())
    
        def get_context_data(self, *args, **kwargs):
            context_data = super(ApplicationCreateView, self).get_context_data(*args, **kwargs)
            context_data.update({'job': self.job})
            return context_data