0

I'm building a job application form. A logged-in user is permitted to apply to the job only once (there's only one job). At the moment, a user is able to directly access the job application (FormView), by typing in its specific URL, and an error message is thrown AFTER the user submits the form. To achieve this, I'm doing a couple of things:

(1) Wrapping the job application view in login_required()

(2) Using the form_valid() method to check whether or not a user has already submitted an application to this specific job via:

def form_valid(self, form):
    form = form.save(commit=False)
    form.user = self.request.user
    if Application.objects.filter(user=user_id):
        messages.error(self.request, 'Sorry, our records show that you have already applied to this job.')
        return redirect('/') 

But I'd rather not permit them to reach the page at all. Instead, I want to check whether or not a user has already applied (during the request), and redirect them away from the form, if they have already applied. I have limited access to logged-in users that pass a test in the past, using something like:

def job_application_view(request):
    active_user = request.user
    if Application.objects.filter(user=active_user):
        return HttpResponse("Some response.")

However, I can't seem to figure out how to access request via the FormView Class-Based View. I'm sure I'm missing something simple. Perhaps another method of FormView I'm missing?

rnevius
  • 26,578
  • 10
  • 58
  • 86

1 Answers1

0

You can still use decorators on class-based views, but they are slightly more difficult to apply than function-based views.

class ApplicationView(FormView):
    # ...

    @method_decorator(user_passes_test(job_application_view))
    def dispatch(self, *args, **kwargs):
        return super(ApplicationView, self).dispatch(*args, **kwargs)

Answering specific parts of your post...

I have limited access to logged-in users that pass a test in the past

With class-based views, you need to decorate the url or decorate the dispatch method with any decorators you are interested in applying.

However, I can't seem to figure out how to access request via the FormView Class-Based View. I'm sure I'm missing something simple. Perhaps another method of FormView I'm missing?

You can access the request with self.request

Community
  • 1
  • 1
Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237