MattG
MattG

Reputation: 1932

How to ensure code runs every time a view is called - Django

With respect to Django generic Views, how do you get a function to run every time a view is called? For example, when I do:

class infoRequestPage(CreateView):
    model = InfoRequest
    form_class = moreInfoForm
    template_name = 'info_request.html'
    success_url = reverse_lazy('HomePageView')

    pageVisit = InfoRequest(
        infoName = autoName,
        infoRegion= autoRegion,)
    pageVisit.save()

    print("test")

It will return test as expected, but only the first time I load the page.However, if I update the source code and change the print command to something different like "testing", it will run again. But like last time, only the first time the page loads. I have tried to clear the cache, and restart browser, but both do nothing. It seems to run only once until the code is changed.

Upvotes: 2

Views: 571

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

You can override the dispatch(…) method [Django-doc]:

class infoRequestPage(CreateView):
    model = InfoRequest
    form_class = moreInfoForm
    template_name = 'info_request.html'
    success_url = reverse_lazy('HomePageView')

    pageVisit = InfoRequest(
        infoName = autoName,
        infoRegion= autoRegion,)
    pageVisit.save()

    def dispatch(self, request, *args, **kwargs):
        print('test')
        super().dispatch(request, *args, **kwargs)

For example the LogoutView [Django-doc] uses this to ensure that it logs out a user before it redirects, or renders a page, regardless whether it is a GET, POST, DELETE, PATCH, etc. request:

class LogoutView(SuccessURLAllowedHostsMixin, TemplateView):
    """
    Log out the user and display the 'You are logged out' message.
    """
    next_page = None
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'registration/logged_out.html'
    extra_context = None
@method_decorator(never_cache)
def <b>dispatch</b>(self, request, *args, **kwargs):
    auth_logout(request)
    next_page = self.get_next_page()
    if next_page:
        # Redirect to this page until the session has been cleared.
        return HttpResponseRedirect(next_page)
    return super().dispatch(request, *args, **kwargs)

# ...</code></pre></blockquote>

Upvotes: 3

HenryM
HenryM

Reputation: 5793

to do this on get do

def get(self, *args, **kwargs):
   print("test")
   return super().get(*args, **kwargs)

and on post

def post(self, *args, **kwargs):
   print("test")
   return super().post(*args, **kwargs)

Upvotes: 2

Related Questions