d1spstack
d1spstack

Reputation: 1380

Fetching current user in Django FormView

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 = '/'

Upvotes: 0

Views: 687

Answers (3)

d1spstack
d1spstack

Reputation: 1380

I found that adding the current user object via get_context_data() and then rendering the template based on {% if current_user.ad_credits > 0 %} was the easiest solution for me. If credits are low the template will only show a notification that the user should top up.

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['current_user'] = self.request.user
    return context

Upvotes: 0

Shayestehhs
Shayestehhs

Reputation: 3

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

Upvotes: 0

lucutzu33
lucutzu33

Reputation: 3700

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

Upvotes: 1

Related Questions