Question

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?

Was it helpful?

Solution 2

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

OTHER TIPS

You may be interested in CreateView page of the fantastic http://ccbv.co.uk/ In this page, you can see in one glance which member methods and variables you can use.

In your case, you will be interested to override:

def get_initial(self):
    # Call parent, add your slug, return data
    initial_data = super(ApplicationCreateView, self).get_initial()
    initial_data['slug'] = ...  # Not sure about the syntax, print and test
    return initial_data

def get_context_data(self, **kwargs):
    # Call parent, add your job object to context, return context
    context = super(ApplicationCreateView, self).get_context_data(**kwargs)
    context['job'] = ...
    return context

This has not been tested at all. You may need to play with it a little. Have fun.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top