Reputation: 93
I am new to django. I am coding a urlshortner now I wanted to ad functionality to read Http referer to count number of times the link has been clicked from various social platforms.
In documentation it states that HttpRequest object that in included in django.http will extract it using - HttpRequest.META['HTTP_REFERER']
So I did this to print out the type of info that it contains -
from django.http import HttpRequest
from .models import UrlSave
def display(request,id):
print(HttpRequest.META['HTTP_REFERER'])
try:
short_url = UrlSave.objects.get(pk=id)
visit_time = short_url.times_visited
short_url.times_visited = short_url.times_visited+1
url = short_url.to_view
short_url.save()
context = {'visit':visit_time,'url':url}
return render(request,'shorturl/previsit.html',context)
except:
return HttpResponse('Wrong Url')
But when I visit the link it prints out the error in CLI - AttributeError: type object 'HttpRequest' has no attribute 'META'
I am unable to find out the reason for it even after going through many stackoverflow pages Please Help
Upvotes: 0
Views: 1513
Reputation: 476537
You can not obtain the META
of the request by accessing it like a class attribute, the specific request is the request
parameter, so you can access it with request.META['HTTP_REFERER']
:
from django.http import HttpRequest
from .models import UrlSave
def display(request, id):
print(request.META['HTTP_REFERER'])
try:
short_url = UrlSave.objects.get(pk=id)
visit_time = short_url.times_visited
short_url.times_visited = short_url.times_visited+1
url = short_url.to_view
short_url.save()
context = {'visit':visit_time,'url':url}
return render(request,'shorturl/previsit.html',context)
except:
return HttpResponse('Wrong Url')
Upvotes: 3