Crazy9
Crazy9

Reputation: 33

How to get the url before render it

I would like to build a system which need to detect which urls the user opened and count the opened times.

There are several different urls shared the same WaitView(TemplateView), so I want to count the numbers for each url when user click it.

I added a dic in the urls and hope it can return the correct url the user opened to the context1 in Waitview.

But I couldn't find a correct way to obtain the correct url, (I tried to use HttpRequest.get_full_path() but it continues error. "TypeError: get_full_path() missing 1 required positional argument: 'self'")

Moreover, I hope the WaitView could received the correct url and count times and then show the times on the opened page.(need the correct url before render it)

So I wander if you have some suggestions on this.

Really appreciate for your kind help.

# urls.py
'''
urlpatterns = [
    re_path('get_times/.+', WaitView.as_view(), {"url": ***CORRECT_URL***})
]

'''



# views.py
'''
class WaitView(TemplateView):
    template_name = 'wait.html'

    def get_context_data(self, **kwargs):
        context1 = kwargs.items()
        print(context1)
'''

Upvotes: 1

Views: 129

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476709

The request object is stored in the .request attribute of a View. You thus can access it with self.request in the view methods, and you thus can obtain the url with:

class WaitView(TemplateView):
    template_name = 'wait.html'

    def get_context_data(self, **kwargs):
        print(self.request.get_full_path())
        return super().get_context_data(**kwargs)

You can use the .build_absolute_uri() method [Django-doc] to generate the absolute URI (so including the protocol, hostname, etc.).

so there is no need to add a parameter to the context.

Upvotes: 1

Related Questions