Home > Software engineering >  Fetching current user in Django FormView
Fetching current user in Django FormView

Time:09-29

Im building a listings site and each user is linked to a company. Before the user can post a new listing it must have bought credits. If there are no credits the FormView should show a template with a notification of 0 credits, however if credits > 0 then the actual form should appear.

Im struggling in trying to fetch the current user in the FormView class itself. I know that it can be done via the form_valid method user = self.request.user, but that would mean that the user must first fill the whole form and submit it after checking if he has enough credits. Im trying to figure out how to perform the check before the form has been filled and submitted. I couldnt find resources how can I do something like this:

class CreateAd(LoginRequiredMixin, FormView):
    if currents_user.ad_credits > 0:
        template_name = 'ads/ad_form.html'
        form_class = AdForm
        success_url = '/'
    else:
        template_name = 'ads/not_enough_credits.html'
        form_class = AdForm
        success_url = '/'

CodePudding user response:

You can use get_form_kwargs:

def get_form_kwargs(self):
    kwargs = super().get_form_kwargs()
    user = self.request.user
    kwargs['initial'] = ... # here update the form kwargs based on user
    return kwargs

CodePudding user response:

You can override 'get' function like this.

def get(self, request, *args, **kwargs):
    if currents_user.ad_credits > 0:
        super(CreateAd, self).get(request, *args, **kwargs)
    else:
        raise HttpResponseBadRequest # Or what kind of error that you like
  • Related